All 5 AI packs for $39 →
← ToolTier Library
Cursor rules · Free

Cursor rules for Django 6 (models, migrations, ORM queries, security)

A free Cursor rule (.mdc) for Django 6.x: generated migrations only and fix-forward, select_related and prefetch_related against N+1 queries, Django 6.1 fetch modes and DB_CASCADE, scoped object lookups, CSRF and autoescape, secrets from env and check --deploy.

Install
.cursor/rules/django.mdc
Last tested
Cursor / Django 6.1.3 docs · 2026-11-26

The costly AI mistakes in a Django project are mostly quiet ones: a hand-edited migration that was already applied in production, a list view that runs one query per row, an object looked up by id without checking who owns it, a csrf_exempt added to make a form work, or |safe on user input. This rule tells Cursor's agent how to avoid each one. It's an Apply to Specific Files rule that attaches when models, migrations, views, forms, admin, URLs, settings, templates or tests are in play.

It follows Django's docs, checked on November 26, 2026, when Django 6.1.3 was the latest release on PyPI. The Django 6.0 release notes say DEFAULT_AUTO_FIELD now defaults to BigAutoField and add built-in Content Security Policy support. The 6.1 release notes add model field fetch modes (FETCH_PEERS works like an on-demand prefetch_related, FETCH_RAISE blocks unintended queries), database-level on_delete options that skip the delete signals, and the MAILERS setting, which deprecates EMAIL_BACKEND and the other EMAIL_ settings. The rule only uses the 6.1 features when the project is on 6.1.

Fill in the [bracketed] Python and Django versions, database, test runner and the way you run manage.py. If you build APIs with FastAPI next to Django, add our free Cursor rules for FastAPI, and if the project is a uv workspace, our AGENTS.md for a Python uv monorepo covers the commands every agent should use.

django.mdc
---
description: Django 6.x conventions for models, migrations, ORM queries, views, settings, security and tests. Use when editing Django apps, models, migrations, views, forms, templates, settings or their tests.
globs: **/models.py, **/models/**/*.py, **/migrations/*.py, **/views.py, **/views/**/*.py, **/forms.py, **/admin.py, **/urls.py, **/settings*.py, **/settings/**/*.py, **/templates/**/*.html, **/tests/**/*.py, **/test_*.py
alwaysApply: false
---

# Django: models, migrations, queries and security

Stack: Python [3.12], Django [6.1], [PostgreSQL], [pytest-django | Django test runner]. Check the installed Django version in `[pyproject.toml | requirements.txt]` before using an API, and never invent a Django setting, field option or management command. If this rule disagrees with the official docs for that version, the docs win.

## Project layout
- `[config/]` holds settings, root `urls.py`, `asgi.py` and `wsgi.py`. Apps live in `[apps/<name>/]` and are listed in `INSTALLED_APPS`.
- Business logic goes in `services.py` or model methods, not in views, signals or templates.
- Run management commands as `[uv run python manage.py <command>]`.

## Models and migrations
- After changing a model, run `makemigrations` for that app and commit the generated migration with the model change. Never hand-write a migration Django can generate.
- Never edit or delete a migration that has already been applied outside your machine. Fix forward with a new migration.
- Data changes go in a separate migration with `RunPython` and a reverse function (or `migrations.RunPython.noop`). Use `apps.get_model()` inside it, never a direct import of the model.
- Adding a non-null column to a big table: add it nullable or with a default first, backfill, then tighten it in a later migration.
- Primary keys default to `BigAutoField` since Django 6.0. Don't add `DEFAULT_AUTO_FIELD` or `default_auto_field` lines unless the project already pins them.
- `on_delete` is required on every `ForeignKey`. On Django 6.1, `DB_CASCADE`, `DB_SET_NULL` and `DB_SET_DEFAULT` run in the database and skip `pre_delete` and `post_delete` signals; don't use them where something relies on those signals.
- `makemigrations --check` must pass before you finish.

## ORM queries
- Avoid N+1 queries: use `select_related()` for foreign keys and one-to-one, and `prefetch_related()` for reverse and many-to-many relations, in any view or loop that touches related objects.
- On Django 6.1, `QuerySet.fetch_mode(models.FETCH_PEERS)` fetches a missing field for every instance from the same QuerySet, and `FETCH_RAISE` raises instead of querying. Only use them if the project is on 6.1 or later.
- Filter in the database, not in Python. Use `exists()` instead of `count() > 0` or loading rows, and `update()` / `bulk_create()` for batch writes.
- Wrap multi-step writes that must succeed together in `transaction.atomic()`.
- Never build SQL with f-strings or `%` formatting. If raw SQL is unavoidable, pass parameters to `raw()` or `cursor.execute()` separately.

## Views, forms and templates
- Validate input with a `Form`, `ModelForm` or the project's serializer. Never trust `request.POST` or `request.GET` directly.
- Use `get_object_or_404()` and scope lookups to what the user may see (e.g. `Order.objects.filter(owner=request.user)`), so one user can't read another's object by changing an id.
- Protect views with `login_required` / `LoginRequiredMixin` and permission checks. Don't rely on hiding links.
- Keep CSRF protection on. Don't add `csrf_exempt` without asking.
- Templates autoescape. Don't use `|safe`, `mark_safe()` or `{% autoescape off %}` on anything that contains user input.

## Settings and secrets
- Read `SECRET_KEY`, database URLs and API keys from environment variables. Never commit real values, and never set `DEBUG = True` or `ALLOWED_HOSTS = ["*"]` in production settings.
- Django 6.0 added built-in Content Security Policy support (`ContentSecurityPolicyMiddleware`, `SECURE_CSP`). Don't loosen a policy that already exists to make a script load; ask first.
- On Django 6.1 the `EMAIL_BACKEND` and `EMAIL_*` settings are deprecated in favor of `MAILERS`. Follow whichever the project already uses and don't mix them.
- Production settings must pass `manage.py check --deploy`.

## Tests
- Every bug fix gets a test that fails without the fix. Use `[pytest -q]` or `[python manage.py test]`.
- Use factories or fixtures for data. Don't depend on test order or on data from another test.
- Use `assertNumQueries` (or pytest-django's `django_assert_num_queries`) to lock in query counts for list views you optimized.

## Before you say you're done
Run `[python manage.py check]`, `[python manage.py makemigrations --check --dry-run]` and the tests for the apps you touched, and say which ones you ran.
Works with: Cursor
CursorDjangoPythonBackend

← More free rules, templates and prompts

+ Your logo here