Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Django Project Structure Analysis

Django Project Structure Analysis

By understanding Django's project structure, we can organize code more efficiently, follow Django's best practices, and build maintainable web applications.

In the previous chapter we learned to use the

django-admin startproject

command to create a new project, Django automatically generates the following basic structure:

myproject/

│

├── manage.py

└── myproject/

    ├── __init__.py

    ├── settings.py

    ├── urls.py

    └── wsgi.py

Use django-admin to create the HelloWorld project:



django-admin startproject HelloWorld

After creation, we can view the project's directory structure:

File/Directory Detailed explanation
manage.py Django's command-line management tool for projects, which wraps django-admin functionality, and automatically sets the DJANGO_SETTINGS_MODULE environment variable to point to the current project's configuration. All project management commands are executed through it, such as:
 - `runserver`:启动开发服务器       

 - `makemigrations`:生成数据库迁移文件       

 - `shell`:启动带 ORM 的 Python shell |

| db.sqlite3 | The SQLite database file used by Django by default, automatically generated after the first execution of the migrate command. Suitable for development environments; for production environments it is recommended to switch to PostgreSQL/MySQL. The file location is defined by settings.py The DATABASES['default']['NAME'] defined. | | __pycache__/ | The bytecode cache directory generated by the Python interpreter, containing .pyc files, used to speed up module loading. No need to commit to version control (should be ignored in .gitignore ). |


Core File Analysis

manage.py

manage.py is the command-line tool entry point of a Django project; it provides many useful commands:

Example

#!/usr/bin/env python

import

os

import

sys

if

name

==

"main"

:

   

os

.

environ

.

setdefault

(

"DJANGO_SETTINGS_MODULE"

,

"myproject.settings"

)

   

try

:

       

from

django.

core

.

management

import

execute_from_command_line

   

except

ImportError

:

       

Handle import errors

       

pass

    execute_from_command_line

(

sys

.

argv

)

Common command examples:

settings.py

settings.py is the configuration file of a Django project, containing all important settings:

Example

Key configuration items explained:

DEBUG

=

True

 

Set to True during development to show detailed errors; in production it must be changed to False

ALLOWED_HOSTS

=

[

]

 

When DEBUG=False you must specify allowed host domains (e.g., ['example.com'])

INSTALLED_APPS

=

[

   

'django.contrib.admin'

,

   

Admin site

   

'django.contrib.auth'

,

   

Authentication system

   

'django.contrib.contenttypes'

,

 

Content types framework

   

'django.contrib.sessions'

,

Session management

   

'django.contrib.messages'

,

Messages framework

   

'django.contrib.staticfiles'

,

 

Static file management

   

You can add custom apps: 'myapp.apps.MyAppConfig'

]

DATABASES

=

{

 

Database configuration

   

'default'

:

{

       

'ENGINE'

:

'django.db.backends.sqlite3'

,

       

'NAME'

: BASE_DIR /

'db.sqlite3'

,

 

Use pathlib syntax

       

MySQL example:

       

'ENGINE': 'django.db.backends.mysql',

       

'NAME': 'mydb',

       

'USER': 'root',

       

'PASSWORD': 'password',

   

}

}

STATIC_URL

=

'/static/'

 

Static file URL prefix

STATICFILES_DIRS

=

[

BASE_DIR /

'static'

]

 

Static file search directories during development

MEDIA_URL

=

'/media/'

 

User-uploaded file URL prefix

MEDIA_ROOT

=

BASE_DIR /

'media'

 

Uploaded file storage path

urls.py (URL dispatch center)

Example

from

django.

contrib

import

admin

from

django.

urls

import

path

,

include

urlpatterns

=

[

    path

(

'admin/'

,

admin.

site

.

urls

)

,

 

Admin routes

    path

(

'blog/'

,

include

(

'blog.urls'

)

)

,

 

Sub-application route distribution

   

path('api/', include('api.urls', namespace='api')),

]

wsgi.py & asgi.py

file Purpose
wsgi.py WSGI (Web Server Gateway Interface) configuration, for traditional synchronous servers (e.g., Gunicorn, uWSGI). In production the project is started through this file.
asgi.py ASGI (Asynchronous Server Gateway Interface) configuration, supporting asynchronous servers (e.g., Daphne, Uvicorn). Used for WebSocket or async views.

Extended directories (not auto-generated, but commonly used)

HelloWorld/

├── apps/               # 推荐:存放所有自定义应用

│   └── blog/          # 示例应用

├── static/             # 静态文件(CSS/JS/图片)

├── media/              # 用户上传文件

├── templates/          # 全局模板目录

└── requirements.txt    # 项目依赖列表

1. apps/ directory (recommended structure)

Manage apps centrally, avoiding scattering them in the project root directory.

You need to configure the Python path in settings.py:



import sys

sys.path.insert(0, os.path.join(BASE_DIR, 'apps'))

2. Static files and media files

urls.py (development environment only)

from django.conf import settings from django.conf.urls.static import static

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


Django App Structure

In Django, a project can contain multiple apps. Use the python manage.py startapp myapp command to create a new app, and the following structure is generated:

myapp/

│

├── migrations/

│   └── __init__.py

├── __init__.py

├── admin.py

├── apps.py

├── models.py

├── tests.py

└── views.py

Main app files

models.py

Define data models, corresponding to database tables:

Example

from

django.

db

import

models

class

Product

(

models.

Model

)

:

    name

=

models.

CharField

(

max_length

=

100

)

    price

=

models.

DecimalField

(

max_digits

=

10

,

decimal_places

=

2

)

    description

=

models.

TextField

(

)

   

   

def

str

(

self

)

:

       

return

self

.

name

views.py

Handle business logic, return responses:

Example

from

django.

shortcuts

import

render

from

.

models

import

Product

def

product_list

(

request

)

:

    products

=

Product.

objects

.

all

(

)

   

return

render

(

request

,

'myapp/product_list.html'

,

{

'products'

: products

}

)

admin.py

Configure the Django admin site:

Example

from

django.

contrib

import

admin

from

.

models

import

Product

@

admin.

register

(

Product

)

class

ProductAdmin

(

admin.

ModelAdmin

)

:

    list_display

=

(

'name'

,

'price'

)


Complete Project Structure Example

The complete structure of a typical Django project is as follows:

myproject/

│

├── manage.py

├── requirements.txt

├── static/

│   ├── css/

│   ├── js/

│   └── images/

├── media/

├── templates/

│   └── base.html

└── myproject/

    ├── __init__.py

    ├── settings.py

    ├── urls.py

    ├── wsgi.py

    └── asgi.py

└── myapp1/

    ├── migrations/

    ├── templates/

    │   └── myapp1/

    ├── __init__.py

    ├── admin.py

    ├── apps.py

    ├── models.py

    ├── tests.py

    ├── urls.py

    └── views.py

└── myapp2/

    └── ... (类似结构)


Important Directory Descriptions

migrations directory

Stores database migration files; Django uses these files to track model changes and synchronize to the database.

static directory

Stores static files (CSS, JavaScript, images, etc.), which are collected to a specified location during deployment.

templates directory

Stores HTML template files; Django uses the template language to dynamically generate pages.

media directory

Stores files uploaded by users; needs to be configured in settings.py:

Example

MEDIA_URL

=

'/media/'

MEDIA_ROOT

=

os

.

path

.

join

(

BASE_DIR

,

'media'

)


Practical Suggestions

  1. Project and app separation: Maintain the independence of each app for easy reuse
  2. Environment Configuration: Use different settings files to distinguish development and production environments
  3. Static file management: Use during development STATICFILES_DIRS, use during production collectstatic
  4. URL design: Define URLs at the app level, then include them at the project level
  5. Template organization: Create a subdirectory for each app to store templates

Production vs Development Environment Differences

File/Configuration Development environment Production environment
DEBUG True(show error details) False(hide errors, log them)
Database SQLite (default) PostgreSQL/MySQL (performance optimization)
Static files runserver Served automatically Use collectstatic Collected to CDN
ALLOWED_HOSTS Empty list or ['localhost'] Must configure domains (e.g., ['example.com'])