Exploring Project Structure - potatoscript/django GitHub Wiki
ποΈ Django Project Structure Overview
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:
Default Project 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
π§βπ» Let's Break Down Each File & Folder
mysite/manage.py
(The Project's Remote Control)
1. 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:
mysite/
(The Inner Project Folder)
2. This folder contains your core project files. These files are used for configuring settings and routing. Let's explore them one by one:
mysite/settings.py
π οΈ 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/'
mysite/urls.py
(Routing URLs)
π 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.
hello/
(Your First App)
3. App Folder: 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.
hello/models.py
(Database Models)
π§ 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.
hello/views.py
(Handling User Requests)
π 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.
hello/urls.py
(App-specific URL Routing)
π οΈ 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.
hello/tests.py
(Testing Your Code)
π§ͺ 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
hello/admin.py
(Admin Panel Configuration)
4. 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.
π Understanding Djangoβs Workflow
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.