-
Notifications
You must be signed in to change notification settings - Fork 0
Exploring Project Structure
When you start a new Django project using the command django-admin startproject mysite
, Django automatically creates a set of files and directories for you. Here's a breakdown of the default structure:
mysite/
│
├── mysite/ # The inner folder containing the core project files
│ ├── __init__.py # Empty file that tells Python this is a package
│ ├── settings.py # Project settings: language, database, etc.
│ ├── urls.py # The URL dispatcher for the project
│ ├── asgi.py # ASGI application setup (for asynchronous support)
│ ├── wsgi.py # WSGI application setup (for synchronous support)
│
├── manage.py # The script used to manage the project (start server, migrate, etc.)
│
└── hello/ # Your app folder (created by `startapp`)
├── __init__.py # Makes this folder a Python package
├── admin.py # Admin panel configurations for this app
├── apps.py # App configuration
├── migrations/ # Database migrations (like a history of schema changes)
├── models.py # Database models for your app
├── tests.py # Tests for your app
├── views.py # Views or functions that handle HTTP requests
└── urls.py # URL patterns specific to this app
This is your main control script. Think of it like a remote to manage your Django project. You'll use it to do tasks like running the development server, running database migrations, creating apps, and more.
-
Command Examples:
- Start the development server:
python manage.py runserver
- Create a new app:
python manage.py startapp myapp
- Run migrations to update the database:
python manage.py migrate
- Start the development server:
This folder contains your core project files. These files are used for configuring settings and routing. Let's explore them one by one:
This file contains all the settings that tell Django how to behave.
-
Secret Key:
Django uses a secret key for security purposes. You should never share this key publicly.
SECRET_KEY = 'your-secret-key-here'
-
Installed Apps:
This is a list of all the apps that are part of your project. These include both built-in Django apps (likedjango.contrib.admin
) and apps you create yourself (likehello
).
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'hello', # This is our app
]
-
Database Configuration:
Django uses a database to store your data (like blog posts, user accounts, etc.). By default, it uses SQLite, a simple database file.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / "db.sqlite3",
}
}
-
Static and Media Files:
Django helps you manage your static files (like CSS, JavaScript) and media files (like images or user uploads).
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
This file defines the URLs (paths) of your website and connects them to views that return the content.
-
Default Project URLs:
It includes the Django admin panel and points the root of the website (/
) to an app (we'll set this up next).
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls), # Admin Panel
path('', include('hello.urls')), # Link to our 'hello' app
]
-
Example URL Routing:
-
path('admin/', admin.site.urls)
— This is the URL for the Django admin panel. -
path('', include('hello.urls'))
— This links to thehello
app’s URL configuration.
-
When you run the command python manage.py startapp hello
, Django creates the hello
app folder, which will contain all your business logic, models, views, and more.
Models are like blueprints for your data. They define the structure of the database tables that hold your data.
Example:
Let’s say you want to store information about blog posts. You can create a Post
model:
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=100) # Title of the post
content = models.TextField() # The content of the post
created_at = models.DateTimeField(auto_now_add=True) # Automatically set the date when post is created
def __str__(self):
return self.title
-
Field Types:
-
CharField
is used for short text (like titles). -
TextField
is used for long text (like the content of a blog post). -
DateTimeField
is used to store date and time values.
-
In Django, views are the functions that handle user requests and return responses. Views take a request, perform actions (like querying the database), and then return an HTTP response.
Here’s an example of a simple view that shows a greeting:
from django.http import HttpResponse
def home(request):
return HttpResponse("Hello, welcome to my Django website!")
- Request: The data Django receives when someone visits your website.
- HttpResponse: The data Django sends back to the user’s browser.
Each app can have its own urls.py
file to define URLs specific to that app. For example, in our hello/urls.py
:
from django.urls import path
from . import views
urlpatterns = [
path('', views.home), # This URL connects to the 'home' view
]
-
path('', views.home)
means that when someone visits the home page, Django will use thehome()
function fromviews.py
to respond.
Django encourages you to write tests to ensure your code works as expected. This file is where you can add tests for your models, views, or any part of the application.
For example, let's test if the home()
view returns the correct response:
from django.test import TestCase
from django.urls import reverse
class HomeViewTests(TestCase):
def test_home_view(self):
response = self.client.get(reverse('home')) # Simulate a GET request to the home page
self.assertEqual(response.status_code, 200) # Assert that the status code is 200 (OK)
self.assertContains(response, "Hello, welcome to my Django website!") # Assert that the response contains this text
The admin panel is a great tool that allows you to manage your app’s data. You can add, edit, and delete data from the database without writing any code.
To use the admin panel, you need to register your models:
from django.contrib import admin
from .models import Post
admin.site.register(Post)
Now, you can go to http://127.0.0.1:8000/admin/
, log in, and manage Post
objects from the browser.
Here’s a simple flow of how a request works in Django:
-
Request: The user enters
http://127.0.0.1:8000/
in their browser. -
URL Routing: Django looks at the
urls.py
file to find which view to call. -
View: The
home()
view is executed, and it sends an HTTP response back to the browser. - Response: The browser shows the "Hello, welcome to my Django website!" message.