agentleFS
theyoungastronautstheyoungastronauts/polaris/skills/django-patterns/SKILL.md

django-patterns

Skill4 starsChanged 3 months agoMITView on GitHub

Django/DRF project conventions: service-layer structure, serializers, thin views, URL namespacing, the canonical /api/v1 API contract, Celery tasks, and testing. Apply when writing or reviewing Django/Python backend code.

29 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use django-tdd, springboot-tdd and 8 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • FaisalAlqarniSkill

    django-tdd

    Django testing strategies with pytest-django, TDD methodology, factory_boy, mocking, coverage, and testing Django REST Framework APIs.

    Also in 6 projects that use this

  • AshfaqbsSkill

    springboot-tdd

    Test-driven development for Spring Boot using JUnit 5, Mockito, MockMvc, Testcontainers, and JaCoCo. Use when adding features, fixing bugs, or refactoring.

    Also in 4 projects that use this

  • LangChainSkill

    docker-patterns

    Best practices for Docker containerization and multi-stage builds

    Also in 5 projects that use this

  • seikaikyoSkill

    fastapi-patterns

    FastAPI + SQLModel + Neon PostgreSQL 後端開發最佳實踐。適用於 Render 部署的 API 服務。涵蓋路由設計、資料庫操作、錯誤處理、認證授權。

    Also in 3 projects that use this

  • royaluniondesign-sysSkill

    deployment-patterns

    Deployment workflows, CI/CD pipeline patterns, Docker containerization, health checks, rollback strategies, and production readiness checklists for web applications.

    Also in 3 projects that use this

  • lodetomasiSkill

    tdd-workflow

    Test-Driven Development workflow with red-green-refactor pattern and best practices

    Also in 5 projects that use this

The file

Show its rules and text

We split this skill into the rules it gives an agent

24 rules. 0 are common, 7 are distinctive, and 17 are very specific to this project.

  • 0

    Common

    Most of the 4 edited versions we read keep these.

  • 7

    Distinctive

    This author's own choices. Worth a look.

  • 17

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    All models inherit from AbstractModel (provides uuid, metadata, created_at, updated_at, silent_save())

    line 19
  2. Very specific:

    Use the inherited uuid field for public-facing IDs, keep integer PKs internal

    line 20
  3. Very specific:

    Add __str__ methods to every model

    line 21
  4. Very specific:

    Use Meta.ordering to define default ordering

    line 22
  5. Very specific:

    Keep models thin — business logic goes in services.py

    line 23
  6. Very specific:

    Use SerializerMethodField sparingly — prefer annotations at the queryset level

    line 33
  7. Very specific:

    Always define fields explicitly (never use __all__)

    line 35
  8. Distinctive:

    Prefer ViewSets for CRUD, APIView for custom actions

    line 38
  9. Very specific:

    Use select_related / prefetch_related on querysets to avoid N+1

    line 39
  10. Very specific:

    Use permission_classes explicitly on every view

    line 41
  11. Distinctive:

    Use DRF routers for ViewSets

    line 46
  12. Very specific:

    Prefix: every endpoint lives under /api/v1 with a trailing slash on every path.

    line 52
  13. Very specific:

    Resource endpoints: follow REST collection/detail conventions under the prefix, keyed by uuid:

    line 70
  14. Very specific:

    Keep tasks in each app's tasks.py

    line 98
  15. Very specific:

    Add RunPython data migrations when needed alongside schema changes

    line 102
  16. Distinctive:

    Never edit a migration that's been pushed to main

    line 103
  17. Very specific:

    Use pytest-django with @pytest.mark.django_db

    line 106
  18. Distinctive:

    Use factory_boy for test data (not fixtures)

    line 107
  19. Very specific:

    Test API endpoints via APIClient — test the contract, not internals

    line 108
  20. Distinctive:

    Test services independently with unit tests (no HTTP layer)

    line 109
  21. Very specific:

    All commands run via make (Docker Compose under the hood) — never run python manage.py directly

    line 113
  22. Very specific:

    Use /django-bootstrap when setting up a new project from scratch

    line 114
  23. Distinctive:

    After completing a backend feature, generate an integration summary:

    line 117
  24. Distinctive:

    Document error response shapes

    line 121

“Common” is measured: kept by at least 6 in 10 of the 4 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Skill: Django Patterns

Purpose

Guide Claude Code when implementing Django/DRF features. Follow these conventions unless the project's CLAUDE.md overrides them.

Project Structure

  • Project settings module is always named project/ (not the service name)
  • Apps live in their own top-level directories
  • Each app has: admin.py, apps.py, models.py, serializers.py, services.py, tasks.py, urls.py, views.py, tests/
  • Tests use a tests/ directory with files per concern: test_models.py, test_views.py, test_services.py

Models

  • All models inherit from AbstractModel (provides uuid, metadata, created_at, updated_at, silent_save())
  • Use the inherited uuid field for public-facing IDs, keep integer PKs internal
  • Add __str__ methods to every model
  • Use Meta.ordering to define default ordering
  • Keep models thin — business logic goes in services.py

Service Layer

  • Each app has a services.py — all business logic lives here, not in views or models
  • Services are classes with external dependencies injected via __init__
  • Views call services; services call models and external APIs
  • This keeps views thin and business logic testable without HTTP

Serializers (DRF)

  • Separate read vs write serializers when shapes differ
  • Use SerializerMethodField sparingly — prefer annotations at the queryset level
  • Validate at the serializer level, not the view level
  • Always define fields explicitly (never use __all__)

Views

  • Prefer ViewSets for CRUD, APIView for custom actions
  • Use select_related / prefetch_related on querysets to avoid N+1
  • Views should only: parse request, call service, return serialized response
  • Use permission_classes explicitly on every view

URLs

  • Each app exports urlpatterns from urls.py
  • project/urls.py aggregates with namespacing: path("api/v1/{app}/", include(({app}_urlpatterns, "{app}")))
  • Use DRF routers for ViewSets

Canonical API Contract

This is the source of truth for the cross-stack API. The Django backend ships exactly this; every decoupled client (Next.js, Flutter) consumes exactly this. Keep paths, identifiers, and payload shapes byte-for-byte consistent with this section — do not restate them differently elsewhere.

Prefix: every endpoint lives under /api/v1 with a trailing slash on every path.

Identifiers: clients only ever see uuid. Models keep an internal integer primary key for FK/index efficiency, but URLs and payloads expose the public uuid field only — never the integer id. Detail routes are keyed on it: path("<uuid:uuid>/", ...).

Auth endpoints:

MethodPathRequestResponse
POST/api/v1/auth/login/{email, password}{access, refresh}
POST/api/v1/auth/refresh/{refresh}{access}
GET/api/v1/auth/me/— (Bearer access token)user object
POST/api/v1/auth/register/{username, email, password, first_name, last_name}{user, tokens: {access, refresh}}
  • Login returns the token pair directly: {access, refresh}.
  • Refresh returns {access} (a new access token from a valid refresh token).
  • Register wraps the created user and its tokens: {user, tokens: {access, refresh}}.
  • The user object (from /api/v1/auth/me/ and inside register's user) is {uuid, username, email, first_name, last_name} — no integer id.

Resource endpoints follow REST collection/detail conventions under the prefix, keyed by uuid:

MethodPathPurpose
GET/api/v1/{resource}/list (paginated)
POST/api/v1/{resource}/create
GET/api/v1/{resource}/<uuid>/retrieve
PATCH/api/v1/{resource}/<uuid>/update
DELETE/api/v1/{resource}/<uuid>/delete

(The self-contained full-stack Next.js app applies the same prefix, uuid, and pagination shape to its own route handlers — e.g. /api/v1/posts — though Next.js route paths omit the trailing slash.)

Pagination: list endpoints are page-number paginated. Query params: page and page_size. Response shape:

{
  "page": 1,
  "count": 42,
  "num_pages": 5,
  "results": [ ... ]
}

count is the total item count across all pages, num_pages the total page count, page echoes the current page, and results holds the current page's items. (This is a custom paginator — not DRF's default {count, next, previous, results}.)

Celery Tasks

  • Use @shared_task(bind=True, max_retries=3, default_retry_delay=60)
  • Tasks call services — no business logic in the task itself
  • Keep tasks in each app's tasks.py

Migrations

  • Review auto-generated migrations before committing
  • Add RunPython data migrations when needed alongside schema changes
  • Never edit a migration that's been pushed to main

Testing

  • Use pytest-django with @pytest.mark.django_db
  • Use factory_boy for test data (not fixtures)
  • Test API endpoints via APIClient — test the contract, not internals
  • Test services independently with unit tests (no HTTP layer)
  • Aim for: service logic tests, serializer validation tests, endpoint integration tests

Development Environment

  • All commands run via make (Docker Compose under the hood) — never run python manage.py directly
  • Use /django-bootstrap when setting up a new project from scratch

Integration Summaries

After completing a backend feature, generate an integration summary:

  • List all new/modified endpoints with method, path, auth requirements
  • Include request/response shapes as JSON examples
  • Note any pagination, filtering, or ordering parameters
  • Document error response shapes
  • Save to docs/integration/[feature-name].md

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.