Run before submitting a PR, after major changes, and before deployment to ensure the quality and security of the Django application.
When to Enable
- Before submitting a Pull Request for a Django project
- After major model changes, migration updates, or dependency upgrades
- Verification before staging or production deployment
- Run the full environment check → code linting → tests → security scan → deployment readiness pipeline
- Verify migration safety and test coverage
Phase 1: Environment Check
# 验证 Python 版本
python --version # 应符合项目要求
Check the virtual environment
which python pip list --outdated
Verify environment variablespython -c "import os; import environ; print('DJANGO_SECRET_KEY set' if os.environ.get('DJANGO_SECRET_KEY') else 'MISSING: DJANGO_SECRET_KEY')"
如果环境配置错误,请停止并修复。
## 阶段 2:代码质量与格式化 (Code Quality & Formatting)
```bash
# 类型检查
mypy . --config-file pyproject.toml
# 使用 ruff 进行 Lint 检查
ruff check . --fix
# 使用 black 进行格式化检查
black . --check
black . # 自动修复
# 导入语句排序
isort . --check-only
isort . # 自动修复
# Django 特有的检查
python manage.py check --deploy
Common issues:
- Missing type hints in public functions
- Violations of PEP 8 formatting standards
- Unsorted import statements
- Debug settings left in production configuration
Phase 3: Database Migrations
# 检查未应用的迁移
python manage.py showmigrations
# 创建缺失的迁移
python manage.py makemigrations --check
# 预演迁移应用 (Dry-run)
python manage.py migrate --plan
# 应用迁移(测试环境)
python manage.py migrate
# 检查迁移冲突
python manage.py makemigrations --merge # 仅在存在冲突时运行
Report:
- Number of pending migrations
- Any migration conflicts
- Model changes without generated migration files
Phase 4: Tests + Coverage
# 使用 pytest 运行所有测试并生成覆盖率报告
pytest --cov=apps --cov-report=html --cov-report=term-missing --reuse-db
# 运行特定应用的测试
pytest apps/users/tests/
# 运行带有标记的测试
pytest -m "not slow" # 跳过慢速测试
pytest -m integration # 仅运行集成测试
# 查看覆盖率报告
open htmlcov/index.html
Report:
- Test totals: X passed, Y failed, Z skipped
- Overall coverage: XX%
- Coverage breakdown by app
Coverage targets:
| Component | Target |
|---|---|
| Models | 90%+ |
| Serializers | 85%+ |
| Views | 80%+ |
| Services | 90%+ |
| Overall | 80%+ |
Phase 5: Security Scan
# 依赖漏洞扫描
pip-audit
safety check --full-report
# Django 安全检查
python manage.py check --deploy
# Bandit 安全 Lint 检查
bandit -r . -f json -o bandit-report.json
# 密钥扫描(如果安装了 gitleaks)
gitleaks detect --source . --verbose
# 环境变量检查
python -c "from django.core.exceptions import ImproperlyConfigured; from django.conf import settings; settings.DEBUG"
Report:
- Vulnerable dependencies found
- Security configuration issues
- Hardcoded secrets detected
- DEBUG mode status (should be False in production)
Phase 6: Django Management Commands
# 检查模型问题
python manage.py check
# 收集静态文件
python manage.py collectstatic --noinput --clear
# 创建超级用户(如测试需要)
echo "from apps.users.models import User; User.objects.create_superuser('admin@example.com', 'admin')" | python manage.py shell
# 数据库完整性检查
python manage.py check --database default
# 缓存验证(如果使用 Redis)
python -c "from django.core.cache import cache; cache.set('test', 'value', 10); print(cache.get('test'))"
Phase 7: Performance Checks
# Django Debug Toolbar 输出(检查 N+1 查询)
# 在 DEBUG=True 的开发模式下运行并访问页面
# 在 SQL 面板中查看重复查询
# 查询计数分析
django-admin debugsqlshell # 如果安装了 django-debug-sqlshell
# 检查缺失的索引
python manage.py shell << EOF
from django.db import connection
with connection.cursor() as cursor:
cursor.execute("SELECT table_name, index_name FROM information_schema.statistics WHERE table_schema = 'public'")
print(cursor.fetchall())
EOF
Report:
- Number of queries per page (typical pages should be < 50)
- Missing database indexes
- Duplicate queries detected
Phase 8: Static Assets
# 检查 npm 依赖(如果使用 npm)
npm audit
npm audit fix
# 构建静态文件(如果使用 webpack/vite)
npm run build
# 验证静态文件
ls -la staticfiles/
python manage.py findstatic css/style.css
Phase 9: Configuration Review
# 在 Python shell 中运行以验证设置
python manage.py shell << EOF
from django.conf import settings
import os
# 关键检查项
checks = {
'DEBUG 为 False': not settings.DEBUG,
'SECRET_KEY 已设置': bool(settings.SECRET_KEY and len(settings.SECRET_KEY) > 30),
'ALLOWED_HOSTS 已设置': len(settings.ALLOWED_HOSTS) > 0,
'HTTPS 已启用': getattr(settings, 'SECURE_SSL_REDIRECT', False),
'HSTS 已启用': getattr(settings, 'SECURE_HSTS_SECONDS', 0) > 0,
'数据库已正确配置': settings.DATABASES['default']['ENGINE'] != 'django.db.backends.sqlite3',
}
for check, result in checks.items():
status = '✓' if result else '✗'
print(f"{status} {check}")
EOF
Phase 10: Logging Configuration
# 测试日志输出
python manage.py shell << EOF
import logging
logger = logging.getLogger('django')
logger.warning('测试警告消息')
logger.error('测试错误消息')
EOF
# 检查日志文件(如果已配置)
tail -f /var/log/django/django.log
Phase 11: API Documentation (if using DRF)
# 生成 Schema
python manage.py generateschema --format openapi-json > schema.json
# 验证 Schema
# 检查 schema.json 是否为有效的 JSON
python -c "import json; json.load(open('schema.json'))"
# 访问 Swagger UI (如果使用 drf-yasg)
# 在浏览器访问 http://localhost:8000/swagger/
Phase 12: Diff Review
# 显示差异统计
git diff --stat
# 显示实际变更内容
git diff
# 显示变更的文件名
git diff --name-only
# 检查常见问题
git diff | grep -i "todo\|fixme\|hack\|xxx"
git diff | grep "print(" # 调试语句
git diff | grep "DEBUG = True" # 调试模式
git diff | grep "import pdb" # 调试器
Checklist:
- No debug statements (print, pdb, breakpoint())
- No TODO/FIXME comments in critical code
- No hardcoded secrets or credentials
- Model changes include database migration files
- Configuration changes are documented
- External calls include error handling
- Transaction management is in place at critical points
Output Template
DJANGO 验证报告
==========================
阶段 1:环境检查
✓ Python 3.11.5
✓ 虚拟环境已激活
✓ 所有环境变量已设置
阶段 2:代码质量
✓ mypy: 无类型错误
✗ ruff: 发现 3 个问题(已自动修复)
✓ black: 无格式问题
✓ isort: 导入语句已正确排序
✓ manage.py check: 无问题
阶段 3:数据库迁移
✓ 无未应用的迁移
✓ 无迁移冲突
✓ 所有模型均有迁移文件
阶段 4:测试 + 覆盖率
测试:247 通过,0 失败,5 跳过
覆盖率:
总体:87%
users: 92%
products: 89%
orders: 85%
payments: 91%
阶段 5:安全扫描
✗ pip-audit: 发现 2 个漏洞(需要修复)
✓ safety check: 无问题
✓ bandit: 无安全问题
✓ 未检测到密钥
✓ DEBUG = False
阶段 6:Django 命令
✓ collectstatic 已完成
✓ 数据库完整性正常
✓ 缓存后端可连接
阶段 7:性能
✓ 未检测到 N+1 查询
✓ 数据库索引已配置
✓ 查询计数在可接受范围内
阶段 8:静态资源
✓ npm audit: 无漏洞
✓ 资源构建成功
✓ 静态文件已收集
阶段 9:配置
✓ DEBUG = False
✓ SECRET_KEY 已配置
✓ ALLOWED_HOSTS 已设置
✓ HTTPS 已启用
✓ HSTS 已启用
✓ 数据库已正确配置
阶段 10:日志
✓ 日志已配置
✓ 日志文件可写
阶段 11:API 文档
✓ Schema 已生成
✓ Swagger UI 可访问
阶段 12:差异审查
变更文件数:12
+450, -120 行
✓ 无调试语句
✓ 无硬编码密钥
✓ 已包含迁移文件
建议:⚠️ 在部署前修复 pip-audit 发现的漏洞
后续步骤:
1. 更新有漏洞的依赖
2. 重新运行安全扫描
3. 部署到预发布环境进行最终测试
Pre-Deployment Checklist
- All tests passed
- Coverage ≥ 80%
- No security vulnerabilities
- No unapplied migrations
- DEBUG = False in production settings
- SECRET_KEY properly configured
- ALLOWED_HOSTS properly set
- Database backups enabled
- Static files collected and served
- Logging configured and working
- Error monitoring (e.g., Sentry, etc.) configured
- CDN configured (if applicable)
- Redis/cache backend configured
- Celery worker running (if applicable)
- HTTPS/SSL configured
- Environment variables documented
Continuous Integration (Continuous Integration)
GitHub Actions example
# .github/workflows/django-verification.yml
name: Django Verification
on: [push, pull_request]
jobs:
verify:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:14
env:
POSTGRES_PASSWORD: postgres
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
steps:
- uses: actions/checkout@v3
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.11'
- name: Cache pip
uses: actions/cache@v3
with:
path: ~/.cache/pip
key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements.txt') }}
- name: Install dependencies
run: |
pip install -r requirements.txt
pip install ruff black mypy pytest pytest-django pytest-cov bandit safety pip-audit
- name: Code quality checks
run: |
ruff check .
black . --check
isort . --check-only
mypy .
- name: Security scan
run: |
bandit -r . -f json -o bandit-report.json
safety check --full-report
pip-audit
- name: Run tests
env:
DATABASE_URL: postgres://postgres:postgres@localhost:5432/test
DJANGO_SECRET_KEY: test-secret-key
run: |
pytest --cov=apps --cov-report=xml --cov-report=term-missing
- name: Upload coverage
uses: codecov/codecov-action@v3
Quick Reference (Quick Reference)
| Check items | Command |
|---|---|
| Environment | python --version |
| Type checking | mypy . |
| Lint check | ruff check . |
| Formatting | black . --check |
| Migrations | python manage.py makemigrations --check |
| Tests | pytest --cov=apps |
| Security | pip-audit && bandit -r . |
| Django check | python manage.py check --deploy |
| Static file collection | python manage.py collectstatic --noinput |
| Diff stats | git diff --stat |
Remember: Automated verification can catch common issues, but it cannot replace manual code review and manual testing in a staging environment.