[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7FEFMWT3T8SFX996XTZQHH1":3,"skill-same:01M7FEFMWT3T8SFX996XTZQHH1":81},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":37,"commitSha":38,"skillDirectory":39,"forksCount":40,"repositoryHtmlUrl":41,"repositoryHomepageUrl":6,"ownerHtmlUrl":42,"ownerBlogUrl":6,"ownerDescription":43,"updatedAt":44,"install":45,"resources":58},"01M7FEFMWT3T8SFX996XTZQHH1","django",null,"Use when building, reviewing, securing, testing or shipping a Django app — models, migrations, QuerySets\u002Fmanagers, FBV\u002FCBV views, forms, the admin, settings split, and Django REST Framework (serializers, ModelViewSet, permissions). NOT async FastAPI\u002FPydantic services (that is `fastapi`), NOT Postgres schema\u002Findex work (that is `postgresdb`).","lza6\u002FArmor-piercing-system-prompts","lza6","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F128880206?v=4","01M7EB3K7WPX5T28EJ2NVHE6EG","Chinese-tingfeng","01M7EB3K97E1KQ16QWKJMFNGX8",11,"MIT","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fdjango\u002FSKILL.md",[],[],"2026-11-16 10:05:34",false,"---\nname: django\ndescription: \"Use when building, reviewing, securing, testing or shipping a Django app — models, migrations, QuerySets\u002Fmanagers, FBV\u002FCBV views, forms, the admin, settings split, and Django REST Framework (serializers, ModelViewSet, permissions). NOT async FastAPI\u002FPydantic services (that is `fastapi`), NOT Postgres schema\u002Findex work (that is `postgresdb`).\"\ntags: [python, django, orm, drf, backend, web]\nrecommends: [postgresdb, secure-coding, deployment, testing-py, api-design]\norigin: risco\n---\n\n# Django web applications\n\nThe single authoritative skill for building, reviewing, securing, testing and shipping a\n**Django** app — the batteries-included, ORM-first, request\u002Fresponse Python framework.\n\nMental model: **a Django project is apps composed of fat-but-thin-enough models (domain +\nquery logic on the model\u002Fmanager), views that orchestrate (FBV\u002FCBV\u002FDRF) and never own SQL,\nan admin\u002Fforms layer, and a settings module split by environment.** The ORM, migrations,\nauth, admin, CSP and the test runner are all first-party. Reach for the framework before you\nadd a dependency.\n\n## Pinned stack (2026-06)\n\n- **Django 5.2 LTS** — the production default. Released 2025-04-02, security fixes until\n  ~April 2028, supports Python 3.10–3.14. New in 5.2: all models auto-imported in `shell`,\n  `CompositePrimaryKey`, `BoundField` customization.\n- **Django 6.0** — released 2025-12-03 (non-LTS, ~8 months until 6.1). Choose it only when you\n  want the new built-in **Tasks framework** (background jobs without Celery) or **native CSP**\n  (`ContentSecurityPolicyMiddleware`, `SECURE_CSP`) and can take the shorter support window.\n  Drops Python 3.10\u002F3.11; supports 3.12–3.14.\n- **Django REST Framework 3.17.1** (2026-03-24) — adds Django 6.0 + Python 3.14 support.\n- Python 3.12+, `pytest-django`, `factory_boy`. ruff\u002Fuv and type-hint policy live in `python`.\n\n**Version rule:** default to 5.2 LTS. Pick 6.0 only for a concrete Tasks\u002FCSP need, and say so.\n\n## Route elsewhere\n\n| Situation | Route to |\n|---|---|\n| Async service, `fastapi`\u002F`pydantic`\u002Fuvicorn, async SQLAlchemy | `fastapi` |\n| Postgres schema design, EXPLAIN ANALYZE, indexing strategy, RLS, pooling | `postgresdb` |\n| Cross-stack OWASP\u002FSTRIDE threat modeling | `secure-coding` |\n| Container\u002FCompose\u002FCI, gunicorn prod tuning, collectstatic pipeline | `deployment` |\n| REST contract design (cursor vs offset, status codes, versioning) | `api-design` |\n| ruff\u002Fuv\u002Fgeneral type hints, packaging | `python` |\n\n## Project shape\n\nSplit settings by environment; never ship one `settings.py` toggled by `DEBUG`.\n\n```text\nsrc\u002F\n  manage.py\n  config\u002F\n    settings\u002F\n      base.py      # shared; reads secrets from os.environ\n      dev.py       # from base import *; DEBUG=True; local hosts\n      prod.py      # from base import *; DEBUG=False; SECURE_*; CSP\n  catalog\u002F         # an app = a bounded domain\n    models.py  managers.py  views.py  serializers.py  urls.py  admin.py\n    migrations\u002F\n    tests\u002F\n```\n\n- Read secrets with `os.environ[\"SECRET_KEY\"]` (or `django-environ`). **Never** commit a\n  literal `SECRET_KEY` — a leaked key forges sessions and signed tokens.\n- Select env via `DJANGO_SETTINGS_MODULE=config.settings.prod`, not an `if DEBUG` branch.\n- One app = one domain. Resist a single `core` app that accretes everything.\n\n## Models\n\nPut domain and query logic on the model and its manager. The view stays thin.\n\n```python\n# managers.py\nfrom django.db import models\n\nclass ArticleQuerySet(models.QuerySet):\n    def published(self):\n        return self.filter(status=Article.Status.PUBLISHED)\n\n    def for_reader(self):  # composes; reused everywhere, tested once\n        return self.published().select_related(\"author\")\n\n# models.py\nclass Article(models.Model):\n    class Status(models.TextChoices):\n        DRAFT = \"draft\", \"Draft\"\n        PUBLISHED = \"published\", \"Published\"\n\n    tenant = models.ForeignKey(\"Tenant\", on_delete=models.CASCADE)\n    slug = models.SlugField()\n    author = models.ForeignKey(\"Author\", on_delete=models.PROTECT)\n    status = models.CharField(max_length=16, choices=Status.choices, default=Status.DRAFT)\n    published_at = models.DateTimeField(null=True, blank=True)\n\n    objects = ArticleQuerySet.as_manager()\n\n    class Meta:\n        constraints = [\n            models.UniqueConstraint(fields=[\"tenant\", \"slug\"], name=\"uniq_tenant_slug\"),\n            models.CheckConstraint(\n                check=models.Q(status=\"draft\") | models.Q(published_at__isnull=False),\n                name=\"published_needs_date\",\n            ),\n        ]\n        indexes = [models.Index(fields=[\"tenant\", \"status\"])]\n```\n\n- **Constraints live in the DB, not just Python.** A `UniqueConstraint`\u002F`CheckConstraint` is\n  enforced under concurrency; a `clean()` check is not. Validate-in-Python-only is a foot-gun.\n- `on_delete` is mandatory and load-bearing: `CASCADE` deletes children, `PROTECT` blocks the\n  delete, `SET_NULL` orphans. Choosing wrong silently destroys data — pick deliberately.\n- Multi-column PK (5.2+): `pk = models.CompositePrimaryKey(\"tenant_id\", \"id\")`.\n- Bad→Good for business logic:\n\n```python\n# Bad: logic in the view — untested, unreusable, duplicated across endpoints\ndef publish(request, pk):\n    a = Article.objects.get(pk=pk)\n    a.status = \"published\"; a.published_at = timezone.now(); a.save()\n\n# Good: a method on the model — one place, testable, reused by view\u002Fadmin\u002Fcommand\nclass Article(models.Model):\n    def publish(self):\n        self.status = self.Status.PUBLISHED\n        self.published_at = timezone.now()\n        self.save(update_fields=[\"status\", \"published_at\"])\n```\n\n## QuerySet performance\n\nThe N+1 is the single most common Django defect: one query for the list, then one more per row.\n\n```python\n# Bad: 1 + N queries — each .author touches the DB inside the loop\nfor a in Article.objects.all():\n    print(a.author.name)\n\n# Good: 2 queries total (FK -> JOIN; reverse\u002FM2M -> second query)\nfor a in Article.objects.select_related(\"author\").prefetch_related(\"tags\"):\n    print(a.author.name, [t.name for t in a.tags.all()])\n```\n\n| You are following | Use | Cost |\n|---|---|---|\n| Forward `ForeignKey` \u002F `OneToOne` | `select_related(...)` | SQL JOIN, 1 query |\n| Reverse FK, `ManyToMany` | `prefetch_related(...)` | 2nd query, joined in Python |\n| Prefetch that itself needs filter\u002Forder | `Prefetch(\"x\", queryset=...)` | controlled 2nd query |\n\n- Need existence, not rows? `qs.exists()`, never `len(qs)` or `if qs.count()`.\n- Need a few columns of a wide row? `.only(\"id\", \"slug\")` \u002F `.defer(\"body\")`.\n- Computed totals belong in the DB: `annotate(...)` \u002F `aggregate(...)`, not a Python loop.\n- Many inserts: `bulk_create(objs)` — one round-trip, not N `.save()` calls.\n- Never `Model.objects.all()` then slice\u002Ffilter in Python; push it into the QuerySet.\n\nDeeper recipes (`assertNumQueries`, `Prefetch`, `.explain()`, ORM indexing) →\n[references\u002Form-performance.md](references\u002Form-performance.md).\n\n## Views & URLs\n\nKeep views thin: validate input, call a model\u002Fmanager method, return a response. No SQL.\n\n| Need | Use |\n|---|---|\n| One bespoke action, custom flow | function-based view (FBV) |\n| Standard list\u002Fdetail\u002Fcreate\u002Fupdate\u002Fdelete on a model | generic CBV (`ListView`, `DetailView`, …) |\n| JSON API consumed by a client\u002FSPA | drop to DRF (do **not** hand-roll `JsonResponse` CRUD) |\n\nFor the DRF surface — serializers, `ModelViewSet`, routers, permissions, throttling,\npagination, filtering, nested-serializer N+1, versioning — see\n[references\u002Fdrf.md](references\u002Fdrf.md). The thin-view rule still holds: a fat serializer that\nwalks relations per row is just an N+1 wearing a tie.\n\n## Migrations\n\n```bash\npython manage.py makemigrations catalog   # generate from model diff\npython manage.py migrate                   # apply\npython manage.py makemigrations --check    # CI gate: fail if a model drifts from migrations\n```\n\n- **Never edit a migration that has been applied anywhere.** Add a new one. Editing rewrites\n  history and breaks every environment that already ran it.\n- Data backfills go through `migrations.RunPython(forward, reverse)` with a reverse, not a\n  one-off script. Use the historical model from `apps.get_model(...)`, not the imported class.\n- Schema changes on a live table that you cannot afford to lock are expand-and-contract; the\n  Postgres-side mechanics (lock modes, batching) live in `postgresdb`.\n\n## Security\n\nSet these in `prod.py`. Then prove it: `python manage.py check --deploy` must come back clean.\n\n| Setting | Value | Why |\n|---|---|---|\n| `DEBUG` | `False` | `True` leaks settings + a stack-trace shell to the world |\n| `ALLOWED_HOSTS` | explicit domains | `['*']` enables Host-header attacks |\n| `SECRET_KEY` | from `os.environ` | a literal in source forges signed cookies\u002Ftokens |\n| `SECURE_SSL_REDIRECT` | `True` | force HTTPS |\n| `SECURE_HSTS_SECONDS` | `31536000` (+ include-subdomains, preload) | the `check --deploy` warning you saw is this being 0 |\n| `SESSION_COOKIE_SECURE` \u002F `CSRF_COOKIE_SECURE` | `True` | stop cookie leak over HTTP |\n| `SECURE_CSP` (Django 6.0) | a real policy + nonce | native CSP; pre-6.0 use `django-csp` |\n\n- CSRF protection is on by default — keep `CsrfViewMiddleware`; do not blanket-exempt views.\n- The ORM parameterizes queries. Only `.raw()`, `.extra()` and `cursor.execute()` with an\n  f-string\u002F`%`-built string reopen SQL injection. Pass params, never interpolate.\n\nFull `SECURE_*` checklist, CSP nonce\u002Freport-only, upload\u002FSSRF, ORM-injection →\n[references\u002Fsecurity.md](references\u002Fsecurity.md).\n\n## Testing\n\n```python\nimport pytest\nfrom rest_framework.test import APIClient\n\n@pytest.mark.django_db\ndef test_owner_only(article, owner):\n    client = APIClient()\n    assert client.get(f\"\u002Fapi\u002Farticles\u002F{article.pk}\u002F\").status_code == 403  # anon\n    client.force_authenticate(owner)\n    assert client.get(f\"\u002Fapi\u002Farticles\u002F{article.pk}\u002F\").status_code == 200\n```\n\n- `pytest-django` + `@pytest.mark.django_db`; run with `--reuse-db` to skip rebuilds locally.\n- `TestCase` wraps each test in a rolled-back transaction (fast). Use `TransactionTestCase`\n  only when you test `on_commit` hooks or real commit behavior.\n- Lock in N+1 fixes with `assertNumQueries(2)` — it fails the build when a relation regresses.\n- Build instances with `factory_boy`, not 30 lines of `Model.objects.create(...)`.\n\nSetup, fixtures, transactional DB, coverage → [references\u002Ftesting.md](references\u002Ftesting.md).\n\n## Background work\n\n| Need | Use |\n|---|---|\n| New project on Django 6.0, simple enqueue-and-forget jobs | the built-in **Tasks framework** |\n| Pre-6.0, or you need schedules\u002Fretries\u002Ffan-out\u002Fresult backends\u002Fworkers at scale | **Celery** |\n\nEither way: enqueue from the model\u002Fservice layer, never block the request thread.\n\n## Anti-patterns\n\n| Anti-pattern | Why it bites | Do instead |\n|---|---|---|\n| Business logic in the view | untested, duplicated across endpoints | method on the model\u002Fmanager |\n| f-string SQL into `.raw()`\u002F`.extra()`\u002F`cursor.execute` | SQL injection | parameterized queries |\n| Looping rows touching `.author` | N+1 queries | `select_related`\u002F`prefetch_related` |\n| `DEBUG=True` in prod | leaks settings + stack traces | `DEBUG=False` in `prod.py` |\n| `SECRET_KEY` literal in source | forged sessions\u002Ftokens | `os.environ` |\n| Validation only in `clean()` | races under concurrency | DB `UniqueConstraint`\u002F`CheckConstraint` |\n| `Model.objects.all()` in a template loop | one query per iteration | prefetch in the view |\n| `ModelViewSet` with no `permission_classes` | endpoint open to the world | explicit permission class |\n| Fat serializer walking relations | N+1 per response | prefetch + `assertNumQueries` |\n| Editing an applied migration | breaks every env that ran it | new migration |\n| `len(qs)` \u002F `qs.count()` to test existence | full fetch\u002FCOUNT | `qs.exists()` |\n| Swallowing `Model.DoesNotExist` silently | hidden bugs | `get_object_or_404` or handle explicitly |\n\n## Verify\n\n`scripts\u002Fverify.sh [TARGET]` greps tracked Django source for high-signal foot-guns:\nFAIL on a literal `SECRET_KEY`, `ALLOWED_HOSTS = ['*']`, or f-string SQL in\n`.raw()`\u002F`.extra()`\u002F`cursor.execute`; WARN on `DEBUG = True` outside a dev settings file and\na `ModelViewSet`\u002F`APIView` with no `permission_classes`. Read-only, exit 0 on a clean or empty\ntarget. It is a lint, not a substitute for `manage.py check --deploy` or the test suite.\n","# Django web applications\n\nThe single authoritative skill for building, reviewing, securing, testing and shipping a\n**Django** app — the batteries-included, ORM-first, request\u002Fresponse Python framework.\n\nMental model: **a Django project is apps composed of fat-but-thin-enough models (domain +\nquery logic on the model\u002Fmanager), views that orchestrate (FBV\u002FCBV\u002FDRF) and never own SQL,\nan admin\u002Fforms layer, and a settings module split by environment.** The ORM, migrations,\nauth, admin, CSP and the test runner are all first-party. Reach for the framework before you\nadd a dependency.\n\n## Pinned stack (2026-06)\n\n- **Django 5.2 LTS** — the production default. Released 2025-04-02, security fixes until\n  ~April 2028, supports Python 3.10–3.14. New in 5.2: all models auto-imported in `shell`,\n  `CompositePrimaryKey`, `BoundField` customization.\n- **Django 6.0** — released 2025-12-03 (non-LTS, ~8 months until 6.1). Choose it only when you\n  want the new built-in **Tasks framework** (background jobs without Celery) or **native CSP**\n  (`ContentSecurityPolicyMiddleware`, `SECURE_CSP`) and can take the shorter support window.\n  Drops Python 3.10\u002F3.11; supports 3.12–3.14.\n- **Django REST Framework 3.17.1** (2026-03-24) — adds Django 6.0 + Python 3.14 support.\n- Python 3.12+, `pytest-django`, `factory_boy`. ruff\u002Fuv and type-hint policy live in `python`.\n\n**Version rule:** default to 5.2 LTS. Pick 6.0 only for a concrete Tasks\u002FCSP need, and say so.\n\n## Route elsewhere\n\n| Situation | Route to |\n|---|---|\n| Async service, `fastapi`\u002F`pydantic`\u002Fuvicorn, async SQLAlchemy | `fastapi` |\n| Postgres schema design, EXPLAIN ANALYZE, indexing strategy, RLS, pooling | `postgresdb` |\n| Cross-stack OWASP\u002FSTRIDE threat modeling | `secure-coding` |\n| Container\u002FCompose\u002FCI, gunicorn prod tuning, collectstatic pipeline | `deployment` |\n| REST contract design (cursor vs offset, status codes, versioning) | `api-design` |\n| ruff\u002Fuv\u002Fgeneral type hints, packaging | `python` |\n\n## Project shape\n\nSplit settings by environment; never ship one `settings.py` toggled by `DEBUG`.\n\n```text\nsrc\u002F\n  manage.py\n  config\u002F\n    settings\u002F\n      base.py      # shared; reads secrets from os.environ\n      dev.py       # from base import *; DEBUG=True; local hosts\n      prod.py      # from base import *; DEBUG=False; SECURE_*; CSP\n  catalog\u002F         # an app = a bounded domain\n    models.py  managers.py  views.py  serializers.py  urls.py  admin.py\n    migrations\u002F\n    tests\u002F\n```\n\n- Read secrets with `os.environ[\"SECRET_KEY\"]` (or `django-environ`). **Never** commit a\n  literal `SECRET_KEY` — a leaked key forges sessions and signed tokens.\n- Select env via `DJANGO_SETTINGS_MODULE=config.settings.prod`, not an `if DEBUG` branch.\n- One app = one domain. Resist a single `core` app that accretes everything.\n\n## Models\n\nPut domain and query logic on the model and its manager. The view stays thin.\n\n```python\n# managers.py\nfrom django.db import models\n\nclass ArticleQuerySet(models.QuerySet):\n    def published(self):\n        return self.filter(status=Article.Status.PUBLISHED)\n\n    def for_reader(self):  # composes; reused everywhere, tested once\n        return self.published().select_related(\"author\")\n\n# models.py\nclass Article(models.Model):\n    class Status(models.TextChoices):\n        DRAFT = \"draft\", \"Draft\"\n        PUBLISHED = \"published\", \"Published\"\n\n    tenant = models.ForeignKey(\"Tenant\", on_delete=models.CASCADE)\n    slug = models.SlugField()\n    author = models.ForeignKey(\"Author\", on_delete=models.PROTECT)\n    status = models.CharField(max_length=16, choices=Status.choices, default=Status.DRAFT)\n    published_at = models.DateTimeField(null=True, blank=True)\n\n    objects = ArticleQuerySet.as_manager()\n\n    class Meta:\n        constraints = [\n            models.UniqueConstraint(fields=[\"tenant\", \"slug\"], name=\"uniq_tenant_slug\"),\n            models.CheckConstraint(\n                check=models.Q(status=\"draft\") | models.Q(published_at__isnull=False),\n                name=\"published_needs_date\",\n            ),\n        ]\n        indexes = [models.Index(fields=[\"tenant\", \"status\"])]\n```\n\n- **Constraints live in the DB, not just Python.** A `UniqueConstraint`\u002F`CheckConstraint` is\n  enforced under concurrency; a `clean()` check is not. Validate-in-Python-only is a foot-gun.\n- `on_delete` is mandatory and load-bearing: `CASCADE` deletes children, `PROTECT` blocks the\n  delete, `SET_NULL` orphans. Choosing wrong silently destroys data — pick deliberately.\n- Multi-column PK (5.2+): `pk = models.CompositePrimaryKey(\"tenant_id\", \"id\")`.\n- Bad→Good for business logic:\n\n```python\n# Bad: logic in the view — untested, unreusable, duplicated across endpoints\ndef publish(request, pk):\n    a = Article.objects.get(pk=pk)\n    a.status = \"published\"; a.published_at = timezone.now(); a.save()\n\n# Good: a method on the model — one place, testable, reused by view\u002Fadmin\u002Fcommand\nclass Article(models.Model):\n    def publish(self):\n        self.status = self.Status.PUBLISHED\n        self.published_at = timezone.now()\n        self.save(update_fields=[\"status\", \"published_at\"])\n```\n\n## QuerySet performance\n\nThe N+1 is the single most common Django defect: one query for the list, then one more per row.\n\n```python\n# Bad: 1 + N queries — each .author touches the DB inside the loop\nfor a in Article.objects.all():\n    print(a.author.name)\n\n# Good: 2 queries total (FK -> JOIN; reverse\u002FM2M -> second query)\nfor a in Article.objects.select_related(\"author\").prefetch_related(\"tags\"):\n    print(a.author.name, [t.name for t in a.tags.all()])\n```\n\n| You are following | Use | Cost |\n|---|---|---|\n| Forward `ForeignKey` \u002F `OneToOne` | `select_related(...)` | SQL JOIN, 1 query |\n| Reverse FK, `ManyToMany` | `prefetch_related(...)` | 2nd query, joined in Python |\n| Prefetch that itself needs filter\u002Forder | `Prefetch(\"x\", queryset=...)` | controlled 2nd query |\n\n- Need existence, not rows? `qs.exists()`, never `len(qs)` or `if qs.count()`.\n- Need a few columns of a wide row? `.only(\"id\", \"slug\")` \u002F `.defer(\"body\")`.\n- Computed totals belong in the DB: `annotate(...)` \u002F `aggregate(...)`, not a Python loop.\n- Many inserts: `bulk_create(objs)` — one round-trip, not N `.save()` calls.\n- Never `Model.objects.all()` then slice\u002Ffilter in Python; push it into the QuerySet.\n\nDeeper recipes (`assertNumQueries`, `Prefetch`, `.explain()`, ORM indexing) →\n[references\u002Form-performance.md](references\u002Form-performance.md).\n\n## Views & URLs\n\nKeep views thin: validate input, call a model\u002Fmanager method, return a response. No SQL.\n\n| Need | Use |\n|---|---|\n| One bespoke action, custom flow | function-based view (FBV) |\n| Standard list\u002Fdetail\u002Fcreate\u002Fupdate\u002Fdelete on a model | generic CBV (`ListView`, `DetailView`, …) |\n| JSON API consumed by a client\u002FSPA | drop to DRF (do **not** hand-roll `JsonResponse` CRUD) |\n\nFor the DRF surface — serializers, `ModelViewSet`, routers, permissions, throttling,\npagination, filtering, nested-serializer N+1, versioning — see\n[references\u002Fdrf.md](references\u002Fdrf.md). The thin-view rule still holds: a fat serializer that\nwalks relations per row is just an N+1 wearing a tie.\n\n## Migrations\n\n```bash\npython manage.py makemigrations catalog   # generate from model diff\npython manage.py migrate                   # apply\npython manage.py makemigrations --check    # CI gate: fail if a model drifts from migrations\n```\n\n- **Never edit a migration that has been applied anywhere.** Add a new one. Editing rewrites\n  history and breaks every environment that already ran it.\n- Data backfills go through `migrations.RunPython(forward, reverse)` with a reverse, not a\n  one-off script. Use the historical model from `apps.get_model(...)`, not the imported class.\n- Schema changes on a live table that you cannot afford to lock are expand-and-contract; the\n  Postgres-side mechanics (lock modes, batching) live in `postgresdb`.\n\n## Security\n\nSet these in `prod.py`. Then prove it: `python manage.py check --deploy` must come back clean.\n\n| Setting | Value | Why |\n|---|---|---|\n| `DEBUG` | `False` | `True` leaks settings + a stack-trace shell to the world |\n| `ALLOWED_HOSTS` | explicit domains | `['*']` enables Host-header attacks |\n| `SECRET_KEY` | from `os.environ` | a literal in source forges signed cookies\u002Ftokens |\n| `SECURE_SSL_REDIRECT` | `True` | force HTTPS |\n| `SECURE_HSTS_SECONDS` | `31536000` (+ include-subdomains, preload) | the `check --deploy` warning you saw is this being 0 |\n| `SESSION_COOKIE_SECURE` \u002F `CSRF_COOKIE_SECURE` | `True` | stop cookie leak over HTTP |\n| `SECURE_CSP` (Django 6.0) | a real policy + nonce | native CSP; pre-6.0 use `django-csp` |\n\n- CSRF protection is on by default — keep `CsrfViewMiddleware`; do not blanket-exempt views.\n- The ORM parameterizes queries. Only `.raw()`, `.extra()` and `cursor.execute()` with an\n  f-string\u002F`%`-built string reopen SQL injection. Pass params, never interpolate.\n\nFull `SECURE_*` checklist, CSP nonce\u002Freport-only, upload\u002FSSRF, ORM-injection →\n[references\u002Fsecurity.md](references\u002Fsecurity.md).\n\n## Testing\n\n```python\nimport pytest\nfrom rest_framework.test import APIClient\n\n@pytest.mark.django_db\ndef test_owner_only(article, owner):\n    client = APIClient()\n    assert client.get(f\"\u002Fapi\u002Farticles\u002F{article.pk}\u002F\").status_code == 403  # anon\n    client.force_authenticate(owner)\n    assert client.get(f\"\u002Fapi\u002Farticles\u002F{article.pk}\u002F\").status_code == 200\n```\n\n- `pytest-django` + `@pytest.mark.django_db`; run with `--reuse-db` to skip rebuilds locally.\n- `TestCase` wraps each test in a rolled-back transaction (fast). Use `TransactionTestCase`\n  only when you test `on_commit` hooks or real commit behavior.\n- Lock in N+1 fixes with `assertNumQueries(2)` — it fails the build when a relation regresses.\n- Build instances with `factory_boy`, not 30 lines of `Model.objects.create(...)`.\n\nSetup, fixtures, transactional DB, coverage → [references\u002Ftesting.md](references\u002Ftesting.md).\n\n## Background work\n\n| Need | Use |\n|---|---|\n| New project on Django 6.0, simple enqueue-and-forget jobs | the built-in **Tasks framework** |\n| Pre-6.0, or you need schedules\u002Fretries\u002Ffan-out\u002Fresult backends\u002Fworkers at scale | **Celery** |\n\nEither way: enqueue from the model\u002Fservice layer, never block the request thread.\n\n## Anti-patterns\n\n| Anti-pattern | Why it bites | Do instead |\n|---|---|---|\n| Business logic in the view | untested, duplicated across endpoints | method on the model\u002Fmanager |\n| f-string SQL into `.raw()`\u002F`.extra()`\u002F`cursor.execute` | SQL injection | parameterized queries |\n| Looping rows touching `.author` | N+1 queries | `select_related`\u002F`prefetch_related` |\n| `DEBUG=True` in prod | leaks settings + stack traces | `DEBUG=False` in `prod.py` |\n| `SECRET_KEY` literal in source | forged sessions\u002Ftokens | `os.environ` |\n| Validation only in `clean()` | races under concurrency | DB `UniqueConstraint`\u002F`CheckConstraint` |\n| `Model.objects.all()` in a template loop | one query per iteration | prefetch in the view |\n| `ModelViewSet` with no `permission_classes` | endpoint open to the world | explicit permission class |\n| Fat serializer walking relations | N+1 per response | prefetch + `assertNumQueries` |\n| Editing an applied migration | breaks every env that ran it | new migration |\n| `len(qs)` \u002F `qs.count()` to test existence | full fetch\u002FCOUNT | `qs.exists()` |\n| Swallowing `Model.DoesNotExist` silently | hidden bugs | `get_object_or_404` or handle explicitly |\n\n## Verify\n\n`scripts\u002Fverify.sh [TARGET]` greps tracked Django source for high-signal foot-guns:\nFAIL on a literal `SECRET_KEY`, `ALLOWED_HOSTS = ['*']`, or f-string SQL in\n`.raw()`\u002F`.extra()`\u002F`cursor.execute`; WARN on `DEBUG = True` outside a dev settings file and\na `ModelViewSet`\u002F`APIView` with no `permission_classes`. Read-only, exit 0 on a clean or empty\ntarget. It is a lint, not a substitute for `manage.py check --deploy` or the test suite.\n",{"name":5,"tags":24,"origin":30,"recommends":31,"description":7},[25,5,26,27,28,29],"python","orm","drf","backend","web","risco",[32,33,34,35,36],"postgresdb","secure-coding","deployment","testing-py","api-design","main","d69096e239f2a89aabc2cd078c47664a9d3b1e11","07-后端与架构\u002Fdjango",3,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts","https:\u002F\u002Fgithub.com\u002Flza6","个人vx：Tf00798\r\n个人✈：@TFGY999","2026-10-08 14:29:22",{"source":8,"skillName":5,"commands":46,"prompt":56,"zipAvailable":57},[47,50,53],{"tool":48,"command":49},"npx","npx skills add lza6\u002FArmor-piercing-system-prompts --skill django",{"tool":51,"command":52},"bunx","bunx skills add lza6\u002FArmor-piercing-system-prompts --skill django",{"tool":54,"command":55},"pnpm","pnpm dlx skills add lza6\u002FArmor-piercing-system-prompts --skill django","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fdjango\u002FSKILL.md",true,[59,65,69,73,77],{"path":60,"resourceType":61,"resourceTypeDesc":62,"sizeBytes":63,"sourceHtmlUrl":64},"evals\u002Fcases.yaml","REFERENCE","参考文档",3124,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fdjango\u002Fevals\u002Fcases.yaml",{"path":66,"resourceType":61,"resourceTypeDesc":62,"sizeBytes":67,"sourceHtmlUrl":68},"evals\u002FREADME.md",900,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fdjango\u002Fevals\u002FREADME.md",{"path":70,"resourceType":61,"resourceTypeDesc":62,"sizeBytes":71,"sourceHtmlUrl":72},"references\u002Fdrf.md",4120,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fdjango\u002Freferences\u002Fdrf.md",{"path":74,"resourceType":61,"resourceTypeDesc":62,"sizeBytes":75,"sourceHtmlUrl":76},"references\u002Form-performance.md",3148,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fdjango\u002Freferences\u002Form-performance.md",{"path":78,"resourceType":61,"resourceTypeDesc":62,"sizeBytes":79,"sourceHtmlUrl":80},"references\u002Ftesting.md",2752,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fdjango\u002Freferences\u002Ftesting.md",[82,89,94,101,108,115],{"skillNo":83,"name":84,"nameZh":6,"description":85,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":86,"categories":87,"keywords":88,"publishedAt":19},"01M7FFG485KY83TD6HSC4YPCMC","obsidian-clipper-template-creator","Guide for creating templates for the Obsidian Web Clipper. Use when you want to create a new clipping template, understand available variables, or format clipped content.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobsidian-clipper-template-creator\u002FSKILL.md",[],[],{"skillNo":90,"name":84,"nameZh":6,"description":85,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":91,"categories":92,"keywords":93,"publishedAt":19},"01M7FFG0T6AZ0STEJPSB3CX84K","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobsidian-clipper-template-creator-antigravity-awesome-skills-main\u002FSKILL.md",[],[],{"skillNo":95,"name":96,"nameZh":6,"description":97,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":98,"categories":99,"keywords":100,"publishedAt":19},"01M7FFFY0QEM14SKWPDYGMXM2P","python-api","Programmatic Object-Detection-Metrics API guidance for BoundingBox, BoundingBoxes, Evaluator, enums, coordinate conversion, AP\u002FmAP semantics, and source-style import diagnostics.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002Fsub-skills\u002Fpython-api\u002FSKILL.md",[],[],{"skillNo":102,"name":103,"nameZh":6,"description":104,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":105,"categories":106,"keywords":107,"publishedAt":19},"01M7FFFVZQZ2GJ0C0TGP7JHD20","file-evaluation","Folder-based PASCAL VOC AP\u002FmAP evaluation from ground-truth and detection text files.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002Fsub-skills\u002Ffile-evaluation\u002FSKILL.md",[],[],{"skillNo":109,"name":110,"nameZh":6,"description":111,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":112,"categories":113,"keywords":114,"publishedAt":19},"01M7FFFSFNYSE77SJ6PE1CK2DA","object-detection-metrics","Guides legacy Object-Detection-Metrics PASCAL VOC AP\u002FmAP evaluation from detection text folders and direct Python API classes.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002FSKILL.md",[],[],{"skillNo":116,"name":117,"nameZh":6,"description":118,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":119,"categories":120,"keywords":121,"publishedAt":19},"01M7FFFP0GCK1RVXBCPQ8APBMT","nx-workspace-patterns","Configure and optimize Nx monorepo workspaces. Use when setting up Nx, configuring project boundaries, optimizing build caching, or implementing affected commands.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fnx-workspace-patterns\u002FSKILL.md",[],[]]