Communitygithub.com

django-verification

Django 專案的驗證循環:遷移、語法檢查、測試與覆蓋率、安全掃描,以及在發佈或 PR 前檢查部署就緒狀態。

django-verification 是什麼?

這個 django-verification 技能提供了一個完整的驗證循環,專為 Django 專案設計,可在發送 Pull Request、重大變更後或部署前執行。它涵蓋了從環境檢查、程式碼品質(mypy、ruff、black、isort)、資料庫遷移、測試與覆蓋率(pytest + pytest-cov)、安全掃描(pip-audit、bandit、gitleaks)到效能檢查、靜態資產驗證、配置審查、日誌設定、API 文件(DRF)以及 Git diff 審查等 12 個階段。每個階段都有對應的 CLI 指令、報告輸出格式和檢查清單,確保開發者能系統性地提升 Django 應用程式的品質與安全性。該技能也提供了 GitHub Actions CI 範例,方便整合到持續整合流程中。整體而言,這是一個實用且全面的自動化驗證工具,幫助開發團隊在部署前發現並修正潛在問題。

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

在你喜歡的 AI 中提問

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

說明文件

Django 驗證循環

在 PR 前、重大變更後以及部署前執行,確保 Django 應用程式的品質與安全性。

何時啟用

  • 在為 Django 專案開啟 Pull Request 之前
  • 在重大的模型變更、遷移更新或依賴套件升級之後
  • 針對暫存環境或正式環境的部署前驗證
  • 執行完整的環境 → 語法檢查 → 測試 → 安全 → 部署就緒流程
  • 驗證遷移安全性與測試覆蓋率

階段 1:環境檢查

# 確認 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')"

若環境設定有誤,請先修正再繼續。

階段 2:程式碼品質與格式化

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

# 使用 ruff 進行語法檢查
ruff check . --fix

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

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

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

常見問題:

  • 公有函式缺少型別提示
  • PEP 8 格式違規
  • 未排序的匯入
  • 在正式環境組態中遺留除錯設定

階段 3:遷移

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

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

# 預覽遷移套用計畫
python manage.py migrate --plan

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

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

報告:

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

階段 4:測試與覆蓋率

# 執行所有測試(使用 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%+

階段 5:安全掃描

# 依賴套件漏洞
pip-audit
safety check --full-report

# Django 安全檢查
python manage.py check --deploy

# Bandit 安全語法檢查器
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)

階段 6: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'))"

階段 7:效能檢查

# 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 個)
  • 遺漏的資料庫索引
  • 偵測到的重複查詢

階段 8:靜態資產

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

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

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

階段 9:組態審查

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

階段 10:日誌設定

# 測試日誌輸出
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

階段 11:API 文件(若使用 DRF)

# 產生架構
python manage.py generateschema --format openapi-json > schema.json

# 驗證架構
# 檢查 schema.json 是否為有效的 JSON
python -c "import json; json.load(open('schema.json'))"

# 存取 Swagger UI(若使用 drf-yasg)
# 在瀏覽器中前往 http://localhost:8000/swagger/

階段 12:差異審查

# 顯示差異統計
it 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 VERIFICATION REPORT
==========================

Phase 1: Environment Check
  ✓ Python 3.11.5
  ✓ Virtual environment active
  ✓ All environment variables set

Phase 2: Code Quality
  ✓ mypy: No type errors
  ✗ ruff: 3 issues found (auto-fixed)
  ✓ black: No formatting issues
  ✓ isort: Imports properly sorted
  ✓ manage.py check: No issues

Phase 3: Migrations
  ✓ No unapplied migrations
  ✓ No migration conflicts
  ✓ All models have migrations

Phase 4: Tests + Coverage
  Tests: 247 passed, 0 failed, 5 skipped
  Coverage:
    Overall: 87%
    users: 92%
    products: 89%
    orders: 85%
    payments: 91%

Phase 5: Security Scan
  ✗ pip-audit: 2 vulnerabilities found (fix required)
  ✓ safety check: No issues
  ✓ bandit: No security issues
  ✓ No secrets detected
  ✓ DEBUG = False

Phase 6: Django Commands
  ✓ collectstatic completed
  ✓ Database integrity OK
  ✓ Cache backend reachable

Phase 7: Performance
  ✓ No N+1 queries detected
  ✓ Database indexes configured
  ✓ Query count acceptable

Phase 8: Static Assets
  ✓ npm audit: No vulnerabilities
  ✓ Assets built successfully
  ✓ Static files collected

Phase 9: Configuration
  ✓ DEBUG = False
  ✓ SECRET_KEY configured
  ✓ ALLOWED_HOSTS set
  ✓ HTTPS enabled
  ✓ HSTS enabled
  ✓ Database configured

Phase 10: Logging
  ✓ Logging configured
  ✓ Log files writable

Phase 11: API Documentation
  ✓ Schema generated
  ✓ Swagger UI accessible

Phase 12: Diff Review
  Files changed: 12
  +450, -120 lines
  ✓ No debug statements
  ✓ No hardcoded secrets
  ✓ Migrations included

RECOMMENDATION: WARNING: Fix pip-audit vulnerabilities before deploying

NEXT STEPS:
1. Update vulnerable dependencies
2. Re-run security scan
3. Deploy to staging for final testing

部署前檢查清單

  • 所有測試通過
  • 覆蓋率 ≥ 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 .
語法檢查ruff 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/claude-api

Anthropic Claude API patterns for Python and TypeScript. Covers Messages API, streaming, tool use, vision, extended thinking, batches, prompt caching, and Claude Agent SDK. Use when building applications with the Claude API or Anthropic SDKs.

affaan-m/everything-claude-code

End-to-end marketing campaign planning and execution. Covers audience research, positioning, campaign angle definition, landing page copy, email sequences, social posts, ad copy, short-form video scripts, and content calendars. Use as the orchestration layer for multi-channel product launches. Use when planning or executing a multi-channel product launch, or producing landing page, email, social, or ad copy.

affaan-m/everything-claude-code

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/everything-claude-code-conventions

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/frontend-design

Create distinctive, production-grade frontend interfaces with high design quality. Use when the user asks to build web components, pages, or applications and the visual direction matters as much as the code quality.

affaan-m/gget

gget CLI and Python workflow for quick genomic database queries, sequence lookup, BLAST-style searches, enrichment checks, and reproducible bioinformatics evidence logs.

affaan-m/literature-review

Systematic literature-review workflow for academic, biomedical, technical, and scientific topics, including search planning, source screening, synthesis, citation checks, and evidence logging.

affaan-m/motion-ui

Production-ready UI motion system for React/Next.js. Use when implementing animations, transitions, or motion patterns.

affaan-m/project-guidelines-example

Example project-specific skill template based on a real production application.

affaan-m/pubmed-database

Direct PubMed and NCBI E-utilities search workflows for biomedical literature, MeSH queries, PMID lookup, citation retrieval, and API-backed literature monitoring.

affaan-m/scholar-evaluation

Structured scholarly-work evaluation for papers, proposals, literature reviews, methods sections, evidence quality, citation support, and research-writing feedback.

affaan-m/uspto-database

USPTO patent and trademark data workflow for official record lookup, PatentSearch queries, TSDR checks, assignment data, and reproducible IP research logs.

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.

相關技能