Django 是基于 Python 的高级 Web Framework,提供了 Web 应用开发所需的主要基础组件,包括 URL Routing、Views、ORM、Authentication、Middleware、Templates 和数据库迁移。
Django 遵循 MTV(Model–Template–View) 架构,与传统 MVC 类似:
- Model:负责数据模型和数据库交互。
- Template:负责 HTML 页面展示。
- View:负责请求处理、业务逻辑和响应生成。
对于前后端分离项目,Django 通常通过 Django REST Framework(DRF)提供 JSON API,Template 的使用则相对较少。
1. Django Project 与 App
Django 使用 Project 和 App 两级结构组织代码。
- Project:整个 Django 应用的配置和入口。
- App:封装某一类业务功能,可以被多个 Project 复用。
创建项目
安装:
pip install django
创建 Project:
django-admin startproject config .
创建 App:
python manage.py startapp users
项目结构:
project/
├── manage.py
├── config/
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ ├── asgi.py
│ └── wsgi.py
│
└── users/
├── __init__.py
├── admin.py
├── apps.py
├── models.py
├── views.py
├── tests.py
└── migrations/
主要文件:
| 文件 | 作用 |
|---|---|
manage.py | Django 命令行管理入口 |
settings.py | Project 配置 |
urls.py | URL 路由入口 |
wsgi.py | WSGI 部署入口 |
asgi.py | ASGI 部署入口 |
models.py | 数据模型 |
views.py | 请求处理逻辑 |
apps.py | App 配置 |
admin.py | Django Admin 注册 |
migrations/ | 数据库迁移文件 |
注册 App
创建 App 后,需要在 settings.py 中注册:
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"users",
]
App 不一定需要独立数据库表或 URL,它只是 Django 组织功能的一种方式。
实际开发中,可以根据业务领域拆分:
apps/
├── users/
├── products/
├── orders/
└── payments/
不建议为每个小功能都创建一个 App,避免过度拆分。
2. Settings:项目配置
settings.py 是 Django 的核心配置文件。
常用配置:
| Setting | 作用 |
|---|---|
DEBUG | 是否启用调试模式 |
SECRET_KEY | 密码签名等安全用途的密钥 |
ALLOWED_HOSTS | 允许访问的 Host |
INSTALLED_APPS | 已注册的 App |
MIDDLEWARE | 中间件列表 |
ROOT_URLCONF | 根路由模块 |
DATABASES | 数据库连接配置 |
TEMPLATES | 模板引擎配置 |
STATIC_URL | 静态资源 URL |
MEDIA_ROOT | 上传文件存储目录 |
TIME_ZONE / USE_TZ | 时间处理设置 |
DATABASES
例如 PostgreSQL:
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": "app_db",
"USER": "app_user",
"PASSWORD": "...",
"HOST": "localhost",
"PORT": "5432",
}
}
实际生产环境应使用环境变量或 Secret 管理敏感配置。
开发与生产环境
import os
DEBUG = os.getenv("DJANGO_DEBUG", "false").lower() == "true"
SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]
ALLOWED_HOSTS = os.getenv(
"DJANGO_ALLOWED_HOSTS",
"localhost,127.0.0.1",
).split(",")
生产环境应注意:
DEBUG=False。SECRET_KEY不应提交到 Git。- 正确设置
ALLOWED_HOSTS。 - 配置 HTTPS、安全 Cookie 和可信代理。
- 静态资源和上传文件应有明确的存储及访问策略。
Settings 与 App Config
settings.py 管理整个 Project 的配置。
apps.py 定义某个 App 的元信息:
from django.apps import AppConfig
class UsersConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "users"
可以通过 AppConfig.ready() 执行部分 App 初始化逻辑,例如注册 Signals。
但不建议在 ready() 中执行数据库查询或耗时任务,因为应用初始化可能发生在多个管理命令和 Worker 进程中。
3. URL Routing:路由分发
Django 使用 URLconf 将 URL 映射到 View。
基础路由
# config/urls.py
from django.urls import path
from users.views import get_user
urlpatterns = [
path("users/<int:user_id>/", get_user),
]
View:
# users/views.py
from django.http import JsonResponse
def get_user(request, user_id):
return JsonResponse({"user_id": user_id})
请求:
GET /users/123/
将调用:
get_user(request, user_id=123)
Path Converters
Django 内置常用路径转换器:
| Converter | 用途 |
|---|---|
str | 不包含 / 的字符串 |
int | 非负整数 |
slug | Slug 字符串 |
uuid | UUID |
path | 可以包含 / 的路径 |
例如:
path("posts/<slug:slug>/", get_post)
path("files/<path:file_path>/", get_file)
include:模块化路由
大型项目通常由每个 App 管理自己的路由。
# users/urls.py
from django.urls import path
from . import views
app_name = "users"
urlpatterns = [
path("<int:user_id>/", views.get_user, name="detail"),
]
Project 入口:
# config/urls.py
from django.urls import include, path
urlpatterns = [
path("api/users/", include("users.urls")),
]
URL Naming 与 reverse
URL 可以使用名称进行反向解析,避免在业务代码中硬编码路径。
from django.urls import reverse
url = reverse("users:detail", kwargs={"user_id": 123})
# "/api/users/123/"
常见方法:
reverse():根据路由名称生成 URL。reverse_lazy():延迟反向解析,常用于类属性或尚未加载 URLconf 的场景。redirect():重定向到 URL 或命名路由。
4. Views:请求处理逻辑
Django View 接收 HttpRequest,返回 HttpResponse。
主要有两种形式:
- Function-Based Views(FBV)。
- Class-Based Views(CBV)。
Function-Based View
from django.http import JsonResponse
def get_user(request, user_id):
if request.method != "GET":
return JsonResponse(
{"error": "Method not allowed"},
status=405,
)
return JsonResponse({
"id": user_id,
"name": "Alice",
})
对于限制 HTTP Method,更推荐使用 Decorator:
from django.views.decorators.http import require_GET
@require_GET
def get_user(request, user_id):
return JsonResponse({"id": user_id})
Class-Based View
使用 View 类组织不同 HTTP Method:
from django.views import View
from django.http import JsonResponse
class UserView(View):
def get(self, request, user_id):
return JsonResponse({"id": user_id})
def post(self, request, user_id):
return JsonResponse(
{"message": "Updated"},
status=200,
)
路由注册:
path("users/<int:user_id>/", UserView.as_view())
as_view() 将类转换为 Django 能够调用的 View。
Generic Class-Based Views
Django 内置一些通用 View:
| View | 作用 |
|---|---|
TemplateView | 渲染模板 |
ListView | 展示对象列表 |
DetailView | 展示单个对象 |
CreateView | 创建对象 |
UpdateView | 修改对象 |
DeleteView | 删除对象 |
这些主要面向 Django Template + Form 的传统 Web 开发。
如果是 JSON REST API,通常使用 DRF 的 APIView、GenericAPIView 或 ViewSet,不需要混用两套通用 View 体系。
5. Request 与 Response
HttpRequest
Django 将传入的 HTTP 请求封装为 HttpRequest 对象。
def example(request):
request.method
request.path
request.GET
request.POST
request.headers
request.body
request.COOKIES
request.FILES
request.user
常见属性:
| 属性 | 含义 |
|---|---|
request.method | HTTP 方法 |
request.GET | Query Parameters |
request.POST | 表单数据 |
request.body | 原始请求体 |
request.headers | HTTP Headers |
request.FILES | 上传文件 |
request.COOKIES | Cookie |
request.user | 当前认证用户 |
request.session | Session 数据 |
注意:request.POST 不是任意 POST 请求的 JSON Body。
如果客户端发送 JSON:
import json
def create_user(request):
data = json.loads(request.body)
普通 Django View 不会像 DRF Serializer 或 FastAPI Pydantic 那样自动完成 JSON Schema 验证。
HttpResponse
返回文本:
from django.http import HttpResponse
def hello(request):
return HttpResponse("Hello World")
返回 JSON:
from django.http import JsonResponse
def hello(request):
return JsonResponse({
"message": "Hello World"
})
常见响应类:
| Response | 作用 |
|---|---|
HttpResponse | 通用 HTTP 响应 |
JsonResponse | JSON 响应 |
HttpResponseRedirect | 重定向 |
StreamingHttpResponse | 流式响应 |
FileResponse | 文件响应 |
render 与 redirect
传统服务端渲染:
from django.shortcuts import render, redirect
def home(request):
return render(
request,
"home.html",
{"title": "Home"},
)
重定向:
def go_home(request):
return redirect("home")
其中 render() 会使用 Django Template Engine 生成 HTML。
6. Middleware:请求与响应处理链
Middleware 是位于 Web Server 和 View 之间的请求处理机制。
常用于:
- Authentication / Session。
- CSRF Protection。
- Security Headers。
- CORS。
- Logging。
- Request Tracking。
- 公共响应处理。
请求处理流程
HTTP Request
↓
SecurityMiddleware
↓
SessionMiddleware
↓
AuthenticationMiddleware
↓
Custom Middleware
↓
URL Routing / View
↓
Custom Middleware
↓
AuthenticationMiddleware
↓
SessionMiddleware
↓
SecurityMiddleware
↓
HTTP Response
这里展示的是简化的 Middleware 调用关系,实际处理链还涉及异常、模板响应等阶段。
请求通常按配置顺序进入 Middleware,响应沿相反方向返回。
自定义 Middleware
import time
class RequestTimingMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
start = time.perf_counter()
response = self.get_response(request)
elapsed = time.perf_counter() - start
response["X-Process-Time"] = str(elapsed)
return response
注册:
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"users.middleware.RequestTimingMiddleware",
]
注意:这只是展示 Middleware 的简化配置。真实项目应保留默认所需的其他 Middleware,例如 CSRF、Common 和 Message Middleware。
Middleware 顺序
顺序可能影响功能。
例如:
SessionMiddleware
↓
AuthenticationMiddleware
AuthenticationMiddleware 依赖 SessionMiddleware 提供的 Session 信息,因此通常必须排在它之后。
Middleware 与 Decorator
- Middleware:处理项目范围内的请求或响应。
- Decorator:针对特定 View 添加逻辑。
例如:
from django.views.decorators.cache import cache_page
@cache_page(60)
def cached_view(request):
...
7. Authentication:身份认证与授权
Django 内置 django.contrib.auth,提供:
- User Model。
- Password Hashing。
- Session Authentication。
- Login / Logout。
- Groups。
- Permissions。
Authentication 与 Authorization
- Authentication:确定用户是谁。
- Authorization:确定用户有哪些权限。
用户认证
from django.contrib.auth import authenticate, login
def login_user(request):
username = request.POST.get("username")
password = request.POST.get("password")
user = authenticate(
request,
username=username,
password=password,
)
if user is not None:
login(request, user)
return redirect("home")
return HttpResponse("Invalid credentials", status=401)
authenticate() 检查凭据,返回 User 或 None。
login() 将用户身份关联到当前 Session。
这里是简化示例;实际登录 Endpoint 需要正确的 Method 限制、CSRF 防护、输入校验和登录失败保护。
当前用户
def profile(request):
if request.user.is_authenticated:
return JsonResponse({
"username": request.user.get_username()
})
return JsonResponse(
{"detail": "Not authenticated"},
status=401,
)
未登录用户通常对应 AnonymousUser。
login_required
from django.contrib.auth.decorators import login_required
@login_required
def profile(request):
...
未认证用户通常会被重定向到登录页面。
如果是 REST API,往往需要返回适合 API 的 401/403 响应,并结合 DRF 的 Authentication / Permission 机制。
Permission
Django 内置基本模型权限:
request.user.has_perm("users.change_profile")
默认模型权限包括:
add
change
delete
view
还可以通过 Group 统一分配权限。
Session Authentication
Django 默认常用的 Session 认证机制:
Username / Password
↓
authenticate()
↓
login()
↓
Session Created
↓
Session Cookie
↓
Subsequent Requests
↓
Session + AuthenticationMiddleware
↓
request.user
浏览器 Cookie 通常存储 Session 标识,而不是直接存储用户密码。
Django 的 Session Authentication、CSRF Protection 和 Cookie 安全配置需要一起考虑。
CSRF Protection
对于基于 Cookie 的认证,浏览器会自动附带 Cookie,因此需要防范跨站请求伪造(CSRF)。
Django 内置:
django.middleware.csrf.CsrfViewMiddleware
HTML 表单通常使用:
{% csrf_token %}
前后端分离的 AJAX 请求则需要按后端约定携带 CSRF Token。
需要注意:CORS 与 CSRF 是不同的安全机制,配置 CORS 不能代替 CSRF 防护。
Custom User Model
如果项目可能需要自定义用户字段、用户名规则或认证结构,通常建议在项目开始时考虑自定义 User Model。
AUTH_USER_MODEL = "users.User"
在已有大量迁移和外键关联后再更换 User Model,操作会明显复杂。
8. Migration:数据库结构迁移
Django Migration 用于管理数据库 Schema 的版本变化。
例如:
# users/models.py
from django.db import models
class Profile(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField(null=True)
makemigrations
python manage.py makemigrations
根据 Model 变化生成 Migration 文件。
例如:
users/migrations/
├── 0001_initial.py
└── 0002_profile_age.py
migrate
python manage.py migrate
执行尚未应用的 Migration,使数据库结构与迁移状态保持一致。
两者区别:
| 命令 | 作用 |
|---|---|
makemigrations | 根据 Model 变更生成迁移文件 |
migrate | 将 Migration 应用到数据库 |
showmigrations | 查看迁移状态 |
sqlmigrate | 查看迁移操作可能生成的 SQL |
migrate app_name 0001 | 迁移到指定版本 |
Migration 的工作机制
models.py
↓
makemigrations
↓
Migration Files
↓
migrate
↓
Database Schema
Django 根据 Model 当前状态和已有 Migration State 的差异生成新的迁移操作。
Migration 文件通常包含:
class Migration(migrations.Migration):
dependencies = [
("users", "0001_initial"),
]
operations = [
...
]
dependencies:依赖的其他 Migration。operations:要执行的 Schema 或数据操作。
Django 通过 django_migrations 表记录已经应用的迁移。
Schema Migration 与 Data Migration
Schema Migration:
CreateModel
AddField
AlterField
RemoveField
Data Migration:
使用 RunPython 等操作迁移已有数据。
例如在新增字段后,为历史记录填充默认业务数据。
Migration 注意事项
- Migration 文件应提交到 Git。
- 不应随意删除已部署环境使用的迁移文件。
- 修改 Model 并不等于自动修改数据库。
- 在生产环境迁移前,应考虑备份、锁表时间和回滚能力。
- 大型数据表新增字段、索引或修改类型,可能带来显著的数据库操作成本。
对于复杂业务系统,Migration 应作为部署流程的一部分进行管理,而不是在生产环境随意手工修改数据库结构。
9. WSGI、ASGI 与 Django 部署
Django 同时支持 WSGI 和 ASGI 部署接口。
WSGI
传统同步 Web Server Interface。
常见组合:
Client
↓
Nginx
↓
Gunicorn
↓
Django WSGI
↓
Database
ASGI
支持异步通信的应用接口。
常见组合:
Client
↓
Nginx
↓
Uvicorn / ASGI Server
↓
Django ASGI
↓
Database
Django 支持异步 View:
async def my_view(request):
...
但这不意味着整个 Django 应用自动变成完全异步。
需要考虑:
- Middleware 是否支持异步。
- 数据库操作是否使用异步接口。
- 是否存在阻塞同步代码。
- ASGI Server 的运行方式。
关于 Gunicorn、Uvicorn、Nginx、Docker 和 CI/CD 的部署细节,可以放到独立文章中,不必在 Django 基础篇重复介绍。
10. Django 请求生命周期
将前面的概念串联起来:
HTTP Request
↓
WSGI / ASGI Server
↓
Django Application
↓
Middleware
↓
URL Resolver
↓
View
├── Business Logic
├── Model / ORM
├── Authentication / Permissions
└── Template / Serialization
↓
HttpResponse
↓
Middleware
↓
HTTP Response
其中需要理解的几个重要边界:
settings.py:决定框架如何配置。urls.py:决定请求由哪个 View 处理。views.py:处理请求并组织业务逻辑。models.py:定义数据模型。middleware:处理跨 View 的公共逻辑。authentication:提供用户身份与权限能力。migrations:管理数据库 Schema 的演进。
这些组件共同构成 Django Web Application 的基础。
总结
| 知识点 | 重要程度 |
|---|---|
| Project / App | 核心 |
| Settings / INSTALLED_APPS | 核心 |
| URL Routing / include / reverse | 核心 |
| FBV / CBV | 核心 |
| HttpRequest / HttpResponse | 核心 |
| Middleware / 顺序 | 核心 |
| Authentication / Session / Permissions | 核心 |
| CSRF Protection | 重要 |
| makemigrations / migrate | 核心 |
| WSGI / ASGI | 重要 |
| Template / Generic Views | 按需 |
| Admin / Signals | 按需 |
Django 最重要的几个概念:
- Project / App:Project 负责整体配置,App 负责模块化业务功能。
- URL Routing / Views:URLconf 负责路由分发,View 负责处理请求并返回响应。
- Middleware:在请求和响应处理链中实现跨业务模块的公共功能。
- Authentication / Session:Django 提供成熟的用户、会话与权限体系。
- Migration:通过版本化迁移文件维护数据库结构变化。
- WSGI / ASGI:决定 Django 如何与应用服务器集成,并影响同步与异步请求的处理方式。
对于以 RESTful API 为主的 Django 项目,下一步应重点掌握 Django ORM 和 Django REST Framework,它们分别解决数据访问与 API 序列化、验证及接口组织的问题。