Communitygithub.com

Django 検証ループ

Djangoプロジェクト向けの検証ループ:マイグレーション、リンター、カバレッジ付きテスト、セキュリティスキャン、リリース前やPR前のデプロイ準備チェックを実行します。

Django 検証ループ とは?

このスキルは、Djangoプロジェクトの品質とセキュリティを確保するために、PR前、大きな変更後、デプロイ前に実行する12フェーズの自動検証パイプラインを提供します。開発者またはAIエージェントは、環境チェック、コード品質(mypy, ruff, black, isort)、マイグレーション、テスト+カバレッジ(pytest)、セキュリティスキャン(pip-audit, bandit)、パフォーマンス分析、静的アセット、設定レビュー、ロギング、APIドキュメント、差分レビューを順に実行できます。各フェーズは具体的なコマンド例と報告テンプレートを含み、GitHub ActionsのCI例も提供します。このスキルはClaude CodeやClineなどのコマンド実行・ファイル編集可能なエージェントで使用され、最終的に「Django Verification Report」を生成し、Pre-Deployment Checklistに基づいてデプロイ準備完了かどうかを判断します。

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

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

Django 検証ループ は何をしますか?

PR前、大きな変更後、デプロイ前に行い、Djangoアプリケーションの品質とセキュリティを確保します。

実行タイミング

  • Djangoプロジェクトのプルリクエストを開く前
  • 大規模なモデル変更、マイグレーション更新、依存関係アップグレード後
  • ステージングまたは本番環境へのデプロイ前検証
  • 環境 → リンター → テスト → セキュリティ → デプロイ準備の完全パイプライン実行
  • マイグレーションの安全性とテストカバレッジの検証

フェーズ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シェルで設定を確認
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: 差分レビュー

# 差分の統計を表示
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検証レポート
==========================

フェーズ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 完了
  ✓ データベース整合性 OK
  ✓ キャッシュバックエンドに到達可能

フェーズ7: パフォーマンス
  ✓ N+1クエリは検出されませんでした
  ✓ データベースインデックスが設定済み
  ✓ クエリ数は許容範囲内

フェーズ8: 静的アセット
  ✓ npm audit: 脆弱性なし
  ✓ アセットのビルド成功
  ✓ 静的ファイルが収集済み

フェーズ9: 設定
  ✓ DEBUG = False
  ✓ SECRET_KEY 設定済み
  ✓ ALLOWED_HOSTS 設定済み
  ✓ HTTPS 有効
  ✓ HSTS 有効
  ✓ データベース設定済み

フェーズ10: ロギング
  ✓ ロギング設定済み
  ✓ ログファイルへの書き込み可能

フェーズ11: APIドキュメント
  ✓ スキーマ生成済み
  ✓ Swagger UI にアクセス可能

フェーズ12: 差分レビュー
  変更ファイル数: 12
  +450, -120 行
  ✓ デバッグ文なし
  ✓ ハードコードされたシークレットなし
  ✓ マイグレーションが含まれている

推奨事項: 警告: デプロイ前に pip-audit の脆弱性を修正してください

次のステップ:
1. 脆弱性のある依存関係を更新
2. セキュリティスキャンを再実行
3. 最終テストのためにステージングにデプロイ

デプロイ前チェックリスト

  • すべてのテストが合格
  • カバレッジ80%以上
  • セキュリティ脆弱性なし
  • 未適用のマイグレーションなし
  • 本番設定で DEBUG = False
  • SECRET_KEY が適切に設定済み
  • ALLOWED_HOSTS が正しく設定済み
  • データベースのバックアップが有効
  • 静的ファイルが収集され、配信されている
  • ロギングが設定され、動作している
  • エラーモニタリング(Sentryなど)が設定済み
  • CDNが設定済み(該当する場合)
  • Redis/キャッシュバックエンドが設定済み
  • Celeryワーカーが実行中(該当する場合)
  • 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.

関連スキル