django-development

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Django Development Guide

Django 开发指南

This skill provides comprehensive guidance for building robust Django web applications following Django 5.2 standards and industry-proven best practices.
本指南提供遵循Django 5.2标准和行业验证最佳实践的稳健Django Web应用构建全面指导。

When to Use This Skill

何时使用本指南

Use this skill when:
  • Starting a new Django project or app
  • Implementing models, views, templates, or forms
  • Configuring Django settings or URL routing
  • Addressing security concerns in Django applications
  • Writing tests or deploying Django applications
  • Following Django conventions and best practices
  • Troubleshooting Django-specific issues
在以下场景使用本指南:
  • 启动新的Django项目或应用
  • 实现模型、视图、模板或表单
  • 配置Django设置或URL路由
  • 解决Django应用中的安全问题
  • 编写测试或部署Django应用
  • 遵循Django约定和最佳实践
  • 排查Django特定问题

Core Principles

核心原则

Convention Over Configuration: Django follows established conventions that reduce boilerplate and decision fatigue. Follow Django patterns rather than reinventing solutions.
DRY (Don't Repeat Yourself): Extract reusable code into models, managers, mixins, template tags, and middleware.
Security by Default: Django provides built-in protection against common vulnerabilities. Never disable security features without understanding the implications.
Explicit is Better Than Implicit: Code should be clear and self-documenting. Use descriptive names and follow Django naming conventions.

约定优于配置:Django遵循既定约定,减少样板代码和决策负担。遵循Django模式而非自行重复造轮子。
DRY(不要重复自己):将可复用代码提取到模型、管理器、混合类、模板标签和中间件中。
默认安全:Django提供内置防护以抵御常见漏洞。在未了解影响的情况下,切勿禁用安全功能。
显式优于隐式:代码应清晰且自文档化。使用描述性命名并遵循Django命名约定。

Development Workflow

开发工作流

Phase 1: Project Planning and Setup

阶段1:项目规划与搭建

1.1 Understand Requirements

1.1 理解需求

Before creating a Django project, clarify:
  • Data models: What entities exist and how do they relate?
  • User interactions: What actions can users perform?
  • Authentication needs: Who can access what?
  • Third-party integrations: External APIs or services needed?
创建Django项目前,明确:
  • 数据模型:存在哪些实体以及它们之间的关系?
  • 用户交互:用户可以执行哪些操作?
  • 认证需求:谁可以访问哪些内容?
  • 第三方集成:是否需要外部API或服务?

1.2 Initialize Project Structure

1.2 初始化项目结构

Create a new Django project:
bash
undefined
创建新的Django项目:
bash
undefined

Create project directory

Create project directory

mkdir myproject cd myproject
mkdir myproject cd myproject

Create virtual environment

Create virtual environment

python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate
python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate

Install Django

Install Django

pip install django
pip install django

Start project

Start project

django-admin startproject config .

**Key distinction**: A project contains configuration and settings, while apps contain specific functionality.
django-admin startproject config .

**关键区别**:项目包含配置和设置,而应用包含特定功能。

1.3 Configure Initial Settings

1.3 配置初始设置

Load the detailed configuration guide: ⚙️ Settings Configuration Reference
Essential initial settings:
  • SECRET_KEY
    : Must be 50+ characters, use environment variables, never commit to version control
  • DEBUG
    : Set to
    False
    in production
  • ALLOWED_HOSTS
    : Configure for your domain
  • DATABASES
    : Configure database connection
  • INSTALLED_APPS
    : Register Django apps and third-party packages
  • MIDDLEWARE
    : Ensure SecurityMiddleware is enabled and properly ordered

加载详细配置指南: ⚙️ 设置配置参考
必备初始设置:
  • SECRET_KEY
    :必须包含50个以上字符,使用环境变量,切勿提交到版本控制系统
  • DEBUG
    :生产环境中设置为
    False
  • ALLOWED_HOSTS
    :为你的域名进行配置
  • DATABASES
    :配置数据库连接
  • INSTALLED_APPS
    :注册Django应用和第三方包
  • MIDDLEWARE
    :确保SecurityMiddleware已启用并正确排序

Phase 2: Data Modeling

阶段2:数据建模

2.1 Design Your Models

2.1 设计模型

Models are the single source of truth for your data. Before coding:
  • Identify entities (User, Post, Comment, etc.)
  • Define relationships (one-to-many, many-to-many, one-to-one)
  • Determine required fields and constraints
  • Plan for data validation and business logic
模型是数据的单一可信来源。编码前:
  • 识别实体(User、Post、Comment等)
  • 定义关系(一对多、多对多、一对一)
  • 确定必填字段和约束
  • 规划数据验证和业务逻辑

2.2 Implement Models

2.2 实现模型

Load the comprehensive models guide: 📊 Models and Database Reference
Model implementation checklist:
  • Use appropriate field types (
    CharField
    ,
    IntegerField
    ,
    ForeignKey
    , etc.)
  • Set field options (
    null
    ,
    blank
    ,
    default
    ,
    unique
    )
  • Define relationships with proper
    related_name
  • Implement
    __str__()
    method for readable representation
  • Add
    get_absolute_url()
    for object URLs
  • Configure
    Meta
    class (
    ordering
    ,
    verbose_name
    , constraints)
  • Create custom managers for reusable queries
  • Override
    save()
    or
    delete()
    for custom behavior (call
    super()
    )
加载综合模型指南: 📊 模型与数据库参考
模型实现检查清单:
  • 使用合适的字段类型(
    CharField
    IntegerField
    ForeignKey
    等)
  • 设置字段选项(
    null
    blank
    default
    unique
  • 使用正确的
    related_name
    定义关系
  • 实现
    __str__()
    方法以获得可读表示
  • 添加
    get_absolute_url()
    用于对象URL
  • 配置
    Meta
    类(
    ordering
    verbose_name
    、约束)
  • 创建自定义管理器以实现可复用查询
  • 重写
    save()
    delete()
    以实现自定义行为(需调用
    super()

2.3 Create and Apply Migrations

2.3 创建并应用迁移

After defining or modifying models:
bash
undefined
定义或修改模型后:
bash
undefined

Create migration files

Create migration files

python manage.py makemigrations
python manage.py makemigrations

Review generated migrations

Review generated migrations

python manage.py sqlmigrate appname 0001
python manage.py sqlmigrate appname 0001

Apply migrations

Apply migrations

python manage.py migrate

**Migration best practices:**
- Review migrations before applying
- Use descriptive migration names with `--name`
- Never edit applied migrations
- Handle data migrations separately
- Test migrations on development data first

---
python manage.py migrate

**迁移最佳实践:**
- 应用前检查迁移内容
- 使用`--name`指定描述性迁移名称
- 切勿编辑已应用的迁移
- 单独处理数据迁移
- 先在开发数据上测试迁移

---

Phase 3: Views and URL Routing

阶段3:视图与URL路由

3.1 Plan Your Views

3.1 规划视图

Views handle request processing and response generation. Determine:
  • Which views are needed (list, detail, create, update, delete)
  • Function-based views (FBVs) vs class-based views (CBVs)
  • Authentication and permission requirements
  • Template rendering vs API responses
视图处理请求并生成响应。确定:
  • 需要哪些视图(列表、详情、创建、更新、删除)
  • 基于函数的视图(FBVs)与基于类的视图(CBVs)的选择
  • 认证和权限要求
  • 模板渲染与API响应的选择

3.2 Implement Views

3.2 实现视图

Load the comprehensive views guide: 🎯 Views and URL Routing Reference
View patterns:
Function-Based Views (FBVs):
  • Simple, explicit, good for unique logic
  • Full control over request handling
  • Use for complex or non-standard workflows
Class-Based Views (CBVs):
  • Reusable, extensible, built-in functionality
  • Generic views for common patterns (ListView, DetailView, CreateView)
  • Use for standard CRUD operations
加载综合视图指南: 🎯 视图与URL路由参考
视图模式:
基于函数的视图(FBVs):
  • 简单、显式,适合独特逻辑
  • 完全控制请求处理
  • 用于复杂或非标准工作流
基于类的视图(CBVs):
  • 可复用、可扩展,内置功能丰富
  • 通用视图适用于常见模式(ListView、DetailView、CreateView)
  • 用于标准CRUD操作

3.3 Configure URL Routing

3.3 配置URL路由

URL configuration best practices:
  • Use descriptive URL patterns with meaningful names
  • Organize URLs by app using
    include()
  • Use path converters (
    <int:pk>
    ,
    <slug:slug>
    )
  • Name all URL patterns for
    reverse()
    and
    {% url %}
  • Keep URLs RESTful and intuitive

URL配置最佳实践:
  • 使用带有意义名称的描述性URL模式
  • 使用
    include()
    按应用组织URL
  • 使用路径转换器(
    <int:pk>
    <slug:slug>
  • 为所有URL模式命名,以便在
    reverse()
    {% url %}
    中使用
  • 保持URL符合RESTful风格且直观

Phase 4: Templates and Forms

阶段4:模板与表单

4.1 Create Templates

4.1 创建模板

Load the templates and forms guide: 🎨 Templates and Forms Reference
Template best practices:
  • Use template inheritance (base template + child templates)
  • Leverage template tags and filters
  • Keep logic minimal (belongs in views/models)
  • Use
    {% static %}
    for static files
  • Take advantage of automatic XSS protection
加载模板与表单指南: 🎨 模板与表单参考
模板最佳实践:
  • 使用模板继承(基础模板 + 子模板)
  • 利用模板标签和过滤器
  • 尽量减少逻辑(逻辑应放在视图/模型中)
  • 使用
    {% static %}
    处理静态文件
  • 利用自动XSS防护

4.2 Build Forms

4.2 构建表单

Form implementation checklist:
  • Use
    ModelForm
    when tied to models
  • Use
    Form
    for non-model forms
  • Implement custom validation with
    clean_<field>()
    methods
  • Add form-level validation with
    clean()
  • Use
    widgets
    to customize form rendering
  • Handle file uploads with proper validation
  • Include CSRF token in templates (
    {% csrf_token %}
    )

表单实现检查清单:
  • 与模型关联时使用
    ModelForm
  • 非模型表单使用
    Form
  • 使用
    clean_<field>()
    方法实现自定义验证
  • 使用
    clean()
    添加表单级验证
  • 使用
    widgets
    自定义表单渲染
  • 正确处理文件上传并验证
  • 在模板中包含CSRF令牌(
    {% csrf_token %}

Phase 5: Security Implementation

阶段5:安全实施

Security must be considered throughout development, not as an afterthought.
Load the comprehensive security guide: 🔒 Security Best Practices Reference
Security checklist:
  • Keep
    SECRET_KEY
    secure and environment-specific
  • Set
    DEBUG = False
    in production
  • Configure
    ALLOWED_HOSTS
    appropriately
  • Enable HTTPS and secure cookies
  • Use CSRF protection (enabled by default)
  • Leverage built-in XSS protection
  • Use QuerySet parameterization (avoid raw SQL)
  • Validate and sanitize user input
  • Implement proper authentication and authorization
  • Limit file upload sizes and types
  • Set appropriate Content Security Policy headers
  • Enable clickjacking protection

安全必须贯穿开发全程,而非事后补充。
加载综合安全指南: 🔒 安全最佳实践参考
安全检查清单:
  • 确保
    SECRET_KEY
    安全且随环境变化
  • 生产环境中设置
    DEBUG = False
  • 合理配置
    ALLOWED_HOSTS
  • 启用HTTPS和安全Cookie
  • 使用CSRF防护(默认已启用)
  • 利用内置XSS防护
  • 使用QuerySet参数化(避免原生SQL)
  • 验证并清理用户输入
  • 实现适当的认证与授权
  • 限制文件上传的大小和类型
  • 设置适当的内容安全策略头
  • 启用点击劫持防护

Phase 6: Testing

阶段6:测试

Load the testing guide: ✅ Testing and Quality Assurance Reference
Testing best practices:
  • Write tests alongside code development
  • Test models, views, forms, and custom logic
  • Use
    TestCase
    for database-touching tests
  • Use
    SimpleTestCase
    for non-database tests
  • Mock external services and APIs
  • Aim for high coverage of critical paths
  • Use Django's test client for view testing
  • Test authentication and permissions
Run tests:
bash
undefined
加载测试指南: ✅ 测试与质量保证参考
测试最佳实践:
  • 代码开发同步编写测试
  • 测试模型、视图、表单和自定义逻辑
  • 涉及数据库的测试使用
    TestCase
  • 非数据库测试使用
    SimpleTestCase
  • 模拟外部服务和API
  • 关键路径追求高覆盖率
  • 使用Django测试客户端测试视图
  • 测试认证与权限
运行测试:
bash
undefined

Run all tests

Run all tests

python manage.py test
python manage.py test

Run specific app tests

Run specific app tests

python manage.py test myapp
python manage.py test myapp

Run with coverage

Run with coverage

coverage run --source='.' manage.py test coverage report

---
coverage run --source='.' manage.py test coverage report

---

Phase 7: Deployment Preparation

阶段7:部署准备

Before deploying to production:
Load the deployment guide: 🚀 Testing and Deployment Reference
Deployment checklist:
  • Run
    python manage.py check --deploy
  • Set
    DEBUG = False
  • Configure production database
  • Set up static file serving (use
    collectstatic
    )
  • Configure media file storage
  • Set secure cookies and HTTPS settings
  • Configure logging
  • Set up error monitoring (Sentry, etc.)
  • Configure caching strategy
  • Review and optimize database queries
  • Set up backup procedures
  • Document deployment process

部署到生产环境前:
加载部署指南: 🚀 测试与部署参考
部署检查清单:
  • 运行
    python manage.py check --deploy
  • 设置
    DEBUG = False
  • 配置生产数据库
  • 配置静态文件服务(使用
    collectstatic
  • 配置媒体文件存储
  • 设置安全Cookie和HTTPS配置
  • 配置日志
  • 设置错误监控(如Sentry等)
  • 配置缓存策略
  • 检查并优化数据库查询
  • 设置备份流程
  • 记录部署流程

Reference Documentation

参考文档

Load these comprehensive guides as needed during development:
开发过程中可按需加载以下综合指南:

Core References

核心参考

  • ⚙️ Settings Configuration - Complete settings guide including database configuration, static files, middleware, internationalization, and environment-specific settings
  • 📊 Models and Database - Comprehensive model development guide covering field types, relationships, Meta options, custom managers, model methods, inheritance patterns, and migrations
  • 🎯 Views and URL Routing - Complete guide to function-based and class-based views, generic views, URL configuration, request/response handling, and middleware
  • 🎨 Templates and Forms - Template inheritance, template tags/filters, context processors, form creation, validation, widgets, and formsets
  • 🔒 Security Best Practices - Comprehensive security guide covering CSRF, XSS, SQL injection, clickjacking, authentication, HTTPS configuration, and common vulnerabilities
  • ✅ Testing and Deployment - Testing strategies, test types, coverage, deployment preparation, production configuration, and monitoring

  • ⚙️ 设置配置 - 完整的设置指南,包括数据库配置、静态文件、中间件、国际化和环境特定设置
  • 📊 模型与数据库 - 综合模型开发指南,涵盖字段类型、关系、Meta选项、自定义管理器、模型方法、继承模式和迁移
  • 🎯 视图与URL路由 - 完整的基于函数和基于类的视图指南、通用视图、URL配置、请求/响应处理和中间件
  • 🎨 模板与表单 - 模板继承、模板标签/过滤器、上下文处理器、表单创建、验证、小部件和表单集
  • 🔒 安全最佳实践 - 综合安全指南,涵盖CSRF、XSS、SQL注入、点击劫持、认证、HTTPS配置和常见漏洞
  • ✅ 测试与部署 - 测试策略、测试类型、覆盖率、部署准备、生产配置和监控

Common Patterns and Quick Reference

常见模式与快速参考

Creating a New App

创建新应用

bash
python manage.py startapp myapp
Then add to
INSTALLED_APPS
in settings.
bash
python manage.py startapp myapp
然后在设置中添加到
INSTALLED_APPS

Basic Model Pattern

基础模型模式

python
from django.db import models

class MyModel(models.Model):
    name = models.CharField(max_length=200)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-created_at']
        verbose_name_plural = "My Models"

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        from django.urls import reverse
        return reverse('mymodel-detail', args=[str(self.id)])
python
from django.db import models

class MyModel(models.Model):
    name = models.CharField(max_length=200)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-created_at']
        verbose_name_plural = "My Models"

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        from django.urls import reverse
        return reverse('mymodel-detail', args=[str(self.id)])

Basic View Pattern

基础视图模式

python
from django.views.generic import ListView, DetailView
from .models import MyModel

class MyModelListView(ListView):
    model = MyModel
    template_name = 'myapp/mymodel_list.html'
    context_object_name = 'items'
    paginate_by = 20

class MyModelDetailView(DetailView):
    model = MyModel
    template_name = 'myapp/mymodel_detail.html'
python
from django.views.generic import ListView, DetailView
from .models import MyModel

class MyModelListView(ListView):
    model = MyModel
    template_name = 'myapp/mymodel_list.html'
    context_object_name = 'items'
    paginate_by = 20

class MyModelDetailView(DetailView):
    model = MyModel
    template_name = 'myapp/mymodel_detail.html'

Basic URL Pattern

基础URL模式

python
from django.urls import path
from . import views

app_name = 'myapp'

urlpatterns = [
    path('', views.MyModelListView.as_view(), name='list'),
    path('<int:pk>/', views.MyModelDetailView.as_view(), name='detail'),
]
python
from django.urls import path
from . import views

app_name = 'myapp'

urlpatterns = [
    path('', views.MyModelListView.as_view(), name='list'),
    path('<int:pk>/', views.MyModelDetailView.as_view(), name='detail'),
]

Basic Template Pattern

基础模板模式

django
{% extends "base.html" %}
{% load static %}

{% block title %}{{ object.name }}{% endblock %}

{% block content %}
<h1>{{ object.name }}</h1>
<p>Created: {{ object.created_at|date:"F d, Y" }}</p>
{% endblock %}

django
{% extends "base.html" %}
{% load static %}

{% block title %}{{ object.name }}{% endblock %}

{% block content %}
<h1>{{ object.name }}</h1>
<p>创建时间:{{ object.created_at|date:"F d, Y" }}</p>
{% endblock %}

Progressive Workflow

渐进式工作流

Django development is iterative. For new features:
  1. Design the data model → Create/update models → Make migrations
  2. Create views → Implement business logic → Handle requests
  3. Configure URLs → Map URLs to views → Name patterns
  4. Build templates → Create HTML with Django template language
  5. Add forms → Handle user input → Validate data
  6. Write tests → Test models, views, forms → Ensure quality
  7. Review security → Check for vulnerabilities → Follow best practices
Remember: Django documentation at https://docs.djangoproject.com/en/5.2/ is comprehensive and should be consulted for detailed API references and advanced topics.
Django开发是迭代过程。针对新功能:
  1. 设计数据模型 → 创建/更新模型 → 生成迁移
  2. 创建视图 → 实现业务逻辑 → 处理请求
  3. 配置URL → 将URL映射到视图 → 命名模式
  4. 构建模板 → 使用Django模板语言创建HTML
  5. 添加表单 → 处理用户输入 → 验证数据
  6. 编写测试 → 测试模型、视图、表单 → 确保质量
  7. 检查安全 → 排查漏洞 → 遵循最佳实践