Communitygithub.com

Django 驗證迴圈

針對 Django 專案在發布或發送 PR 前,執行遷移、 linting、測試含覆蓋率、安全掃描及部署就緒檢查的驗證迴圈。

Django 驗證迴圈 是什麼?

這項技能提供了一套完整的 Django 驗證流程,專為開發者與 AI 代理設計,用於在合併 PR 或部署前確保 Django 應用程式的品質與安全性。流程涵蓋環境檢查、程式碼品質(mypy、Ruff、black)、資料庫遷移驗證、測試與覆蓋率(pytest)、安全掃描(pip-audit、bandit)、效能檢查(N+1 查詢分析)、靜態資源建置、設定審查、日誌紀錄以及 API 文件生成。支援本機開發環境與 CI/CD 管道(內含 GitHub Actions 範例)。結構化的階段式方法可及早發現常見的 Django 陷阱,例如未套用的遷移、生產環境中殘留的 DEBUG 模式、弱安全性設定、硬編碼密碼以及測試覆蓋率不足。每個階段都會產出包含通過/失敗狀態的報告,最終提供部署推薦與後續步驟清單,協助團隊維持穩定的發佈節奏。

相容平台~Claude Code~Codex CLI✓Cursor
npx skills add https://github.com/affaan-m/ECC/tree/main/skills/django-verification

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

Django 驗證迴圈 是做什麼的?

在發送 PR 前、進行重大修改後以及預先部署時執行,以確保 Django 應用程式的品質與安全性。

啟用時機

  • 針對 Django 專案開啟拉取請求(Pull Request)之前
  • 在重大模型變更、遷移更新或相依套件升級之後
  • 預先部署驗證至暫存(Staging)或正式(Production)環境
  • 執行完整流程:環境檢查 → lint → 測試 → 安全 → 部署就緒管道
  • 驗證遷移安全性與測試覆蓋率

第一階段:環境檢查

# 驗證 Python 版本
python --version  # 應符合專案需求

# 檢查虛擬環境
which python
pip list --outdated

# 驗證環境變數
python -c "import os; import environ; print('DJANGO_SECRET_KEY set' if os.environ.get('DJANGO_SECRET_KEY') else 'MISSING: DJANGO_SECRET_KEY')"

若環境設定錯誤,請停止並修正。

第二階段:程式碼品質與格式化

# 型別檢查
mypy . --config-file pyproject.toml

# 使用 Ruff 進行 lint
ruff check . --fix

# 使用 Black 格式化
black . --check
black .  # 自動修正

# 匯入排序
isort . --check-only
isort .  # 自動修正

# Django 專用檢查
python manage.py check --deploy

常見問題:

  • 公開函數缺少型別註記
  • PEP 8 格式違規
  • 未排序的匯入
  • 正式組態中遺留除錯設定

第三階段:遷移

# 檢查未套用的遷移
python manage.py showmigrations

# 建立遺漏的遷移
python manage.py makemigrations --check

# 預演遷移套用
python manage.py migrate --plan

# 套用遷移(測試環境)
python manage.py migrate

# 檢查遷移衝突
python manage.py makemigrations --merge  # 僅在有衝突時執行

報告項目:

  • 待處理遷移數量
  • 任何遷移衝突
  • 無對應遷移的模型變更

第四階段:測試 + 覆蓋率

# 使用 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

報告項目:

  • 總測試數:X 通過,Y 失敗,Z 跳過
  • 整體覆蓋率:XX%
  • 各應用程式覆蓋率細項

覆蓋率目標:

元件目標
模型90%+
序列化器85%+
檢視80%+
服務90%+
整體80%+

第五階段:安全掃描

# 相依套件漏洞
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"

報告項目:

  • 發現的脆弱相依套件
  • 安全性設定問題
  • 偵測到的硬編碼機密
  • DEBUG 模式狀態(正式環境應為 False)

第六階段:Django 管理命令

# 檢查模型問題
python manage.py check

# 收集靜態檔案
python manage.py collectstatic --noinput --clear

# 建立超級使用者(若測試需要)
echo "from apps.users.models import User; User.objects.create_superuser('[email protected]', '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'))"

第七階段:效能檢查

# 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

報告項目:

  • 每頁查詢數量(一般頁面應 < 50)
  • 遺失的資料庫索引
  • 偵測到的重複查詢

第八階段:靜態資源

# 檢查 npm 相依套件(若使用 npm)
npm audit
npm audit fix

# 建置靜態檔案(若使用 webpack/vite)
npm run build

# 驗證靜態檔案
ls -la staticfiles/
python manage.py findstatic css/style.css

第九階段:組態審查

# 在 Python shell 中執行以驗證設定
python manage.py shell << EOF
from django.conf import settings
import os

# 關鍵檢查
checks = {
    'DEBUG is False': not settings.DEBUG,
    'SECRET_KEY set': bool(settings.SECRET_KEY and len(settings.SECRET_KEY) > 30),
    'ALLOWED_HOSTS set': len(settings.ALLOWED_HOSTS) > 0,
    'HTTPS enabled': getattr(settings, 'SECURE_SSL_REDIRECT', False),
    'HSTS enabled': getattr(settings, 'SECURE_HSTS_SECONDS', 0) > 0,
    'Database configured': settings.DATABASES['default']['ENGINE'] != 'django.db.backends.sqlite3',
}

for check, result in checks.items():
    status = '✓' if result else '✗'
    print(f"{status} {check}")
EOF

第十階段:日誌設定

# 測試日誌輸出
python manage.py shell << EOF
import logging
logger = logging.getLogger('django')
logger.warning('Test warning message')
logger.error('Test error message')
EOF

# 檢查日誌檔案(若有設定)
tail -f /var/log/django/django.log

第十一階段:API 文件(若使用 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/

第十二階段:差異審查

# 顯示差異統計
 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"  # 除錯器

檢查清單:

  • 無除錯陳述(print、pdb、breakpoint())
  • 關鍵程式碼中無 TODO/FIXME 註解
  • 無硬編碼機密或憑證
  • 模型變更已包含資料庫遷移
  • 組態變更已記錄
  • 外部呼叫已包含錯誤處理
  • 必要處已使用交易管理

輸出範本

DJANGO 驗證報告
==========================

第一階段:環境檢查
  ✓ Python 3.11.5
  ✓ 虛擬環境啟用
  ✓ 所有環境變數已設定

第二階段:程式碼品質
  ✓ mypy:無型別錯誤
  ✗ ruff:發現 3 個問題(已自動修正)
  ✓ black:無格式問題
  ✓ isort:匯入已正確排序
  ✓ manage.py check:無問題

第三階段:遷移
  ✓ 無未套用的遷移
  ✓ 無遷移衝突
  ✓ 所有模型都有對應遷移

第四階段:測試 + 覆蓋率
  測試:247 通過,0 失敗,5 跳過
  覆蓋率:
    整體:87%
    users:92%
    products:89%
    orders:85%
    payments:91%

第五階段:安全掃描
  ✗ pip-audit:發現 2 個漏洞(需修正)
  ✓ safety check:無問題
  ✓ bandit:無安全問題
  ✓ 未偵測到機密
  ✓ DEBUG = False

第六階段:Django 命令
  ✓ collectstatic 完成
  ✓ 資料庫完整性 OK
  ✓ 快取後端可連線

第七階段:效能
  ✓ 未偵測到 N+1 查詢
  ✓ 資料庫索引已設定
  ✓ 查詢數量可接受

第八階段:靜態資源
  ✓ npm audit:無漏洞
  ✓ 資源建置成功
  ✓ 靜態檔案已收集

第九階段:組態
  ✓ DEBUG = False
  ✓ SECRET_KEY 已設定
  ✓ ALLOWED_HOSTS 已設定
  ✓ HTTPS 已啟用
  ✓ HSTS 已啟用
  ✓ 資料庫已設定

第十階段:日誌
  ✓ 日誌已設定
  ✓ 日誌檔案可寫入

第十一階段:API 文件
  ✓ Schema 已產生
  ✓ Swagger UI 可存取

第十二階段:差異審查
  變更檔案數:12
  +450, -120 行
  ✓ 無除錯陳述
  ✓ 無硬編碼機密
  ✓ 已包含遷移

建議:警告:部署前請先修正 pip-audit 漏洞

後續步驟:
1. 更新脆弱相依套件
2. 重新執行安全掃描
3. 部署至暫存環境進行最終測試

預先部署檢查清單

  • 所有測試通過
  • 覆蓋率 ≥ 80%
  • 無安全性漏洞
  • 無未套用的遷移
  • 正式組態中 DEBUG = False
  • SECRET_KEY 已正確設定
  • ALLOWED_HOSTS 已正確設定
  • 資料庫備份已啟用
  • 靜態檔案已收集並提供服務
  • 日誌已設定且正常運作
  • 錯誤監控(Sentry 等)已設定
  • CDN 已設定(如適用)
  • Redis/快取後端已設定
  • Celery worker 正在執行(如適用)
  • HTTPS/SSL 已設定
  • 環境變數已文件化

持續整合

GitHub Actions 範例

# .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

快速參考

檢查項目指令
環境python --version
型別檢查mypy .
Lintingruff check .
格式化black . --check
遷移python manage.py makemigrations --check
測試pytest --cov=apps
安全pip-audit && bandit -r .
Django 檢查python manage.py check --deploy
收集靜態檔案python manage.py collectstatic --noinput
差異統計git diff --stat

請記住:自動化驗證能捕捉常見問題,但無法取代人工程式碼審查和在暫存環境中的測試。

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/content-engine

Create platform-native content systems for X, LinkedIn, TikTok, YouTube, newsletters, and repurposed multi-platform campaigns. Use when the user wants social posts, threads, scripts, content calendars, or one source asset adapted cleanly across platforms.

affaan-m/ECC

Multi-platform content distribution across X, LinkedIn, Threads, and Bluesky. Adapts content per platform using content-engine patterns. Never posts identical content cross-platform. Use when the user wants to distribute content across social platforms.

affaan-m/fal-ai-media

Unified media generation via fal.ai MCP — image, video, and audio. Covers text-to-image (Nano Banana), text/image-to-video (Seedance, Kling, Veo 3), text-to-speech (CSM-1B), and video-to-audio (ThinkSound). Use when the user wants to generate images, videos, or audio with AI.

affaan-m/manim-video

日本語翻訳:このファイルは manim-video 用の日本語翻訳が必要です

affaan-m/remotion-video-creation

Remotion のベストプラクティス - React で動画を作成する。3D、アニメーション、音声、字幕、チャート、トランジションなどをカバーするドメイン固有の29のルール。

affaan-m/video-editing

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

agent-self-evaluation

Use after completing any non-trivial task. The agent self-rates its output on 5 axes — accuracy, completeness, clarity, actionability, conciseness — with concrete evidence per criterion. Produces a structured 1-5 scorecard with specific improvement suggestions.

agent-sort

Build an evidence-backed ECC install plan for a specific repo by sorting skills, commands, rules, hooks, and extras into DAILY vs LIBRARY buckets using parallel repo-aware review passes. Use when ECC should be trimmed to what a project actually needs instead of loading the full bundle.

ai-first-engineering

Engineering operating model for teams where AI agents generate a large share of implementation output. Use when setting team process, review gates, or ownership rules for a codebase largely written by agents.

ai-regression-testing

Regression testing strategies for AI-assisted development. Sandbox-mode API testing without database dependencies, automated bug-check workflows, and patterns to catch AI blind spots where the same model writes and reviews code. Use when adding regression coverage to AI-assisted code, or when the same model both wrote and reviewed a change.

android-clean-architecture

Clean Architecture patterns for Android and Kotlin Multiplatform projects — module structure, dependency rules, UseCases, Repositories, and data layer patterns. Use when structuring modules, layers, or data flow in an Android or KMP project.

angular-developer

Generates Angular code and provides architectural guidance. Trigger when creating projects, components, or services, or for best practices on reactivity (signals, linkedSignal, resource), forms, dependency injection, routing, SSR, accessibility (ARIA), animations, styling (component styles, Tailwind CSS), testing, or CLI tooling.

相關技能