Cursor rule for Django apps covering thin views, custom QuerySets, N+1 prevention, careful signals, safe migrations, DRF basics and query-count tests.
.cursor/rules/python-django-patterns.mdc. Downloaded files need to be placed in that repository path.---
description: "Cursor rule for Django apps covering thin views, custom QuerySets, N+1 prevention, careful signals, safe migrations, DRF basics and query-count tests."
globs: "**/*"
alwaysApply: false
---
# Django Application Patterns
Applies to: Django projects (views, querysets, migrations, signals, tests and optional Django REST framework APIs). Model field design is covered by a separate model rule.
Version baseline: checked against the Django stable documentation (6.1; 5.2 is the current LTS). Read the pinned Django version in `pyproject.toml` or `requirements*.txt` and follow its documentation if it differs.
## Project structure
- Split code into apps by domain (`orders`, `billing`, `accounts`), not by technical layer. Each app owns its models, migrations, admin, views, urls and tests.
- Keep settings environment-driven: `SECRET_KEY`, database credentials and `DEBUG` come from the environment, never from committed files. Run `python manage.py check --deploy` against production settings.
- Put multi-model business operations in plain functions (for example `orders/services.py`) wrapped in `transaction.atomic()`. Views and serializers stay thin.
## Views
- Use function-based views for one-off logic, and generic class-based views (`ListView`, `DetailView`, `CreateView`, ...) when they remove real boilerplate. Pick one style per app; do not mix both for the same kind of view.
- Fetch single objects with `get_object_or_404`. Enforce permissions in the view (`LoginRequiredMixin`, `PermissionRequiredMixin`, `@login_required`) and also check object ownership. Login alone is not authorization.
- Use Django forms or DRF serializers for input validation. Never trust `request.POST` or `request.data` directly.
## Querysets and managers
Put reusable filters on a custom `QuerySet` and expose it as the manager, so the filters can be chained:
```python
from django.db import models
class OrderQuerySet(models.QuerySet):
def paid(self):
return self.filter(status=Order.Status.PAID)
def for_customer(self, user):
return self.filter(customer=user)
def with_lines(self):
return self.select_related("customer").prefetch_related("lines__product")
class Order(models.Model):
class Status(models.TextChoices):
PENDING = "pending"
PAID = "paid"
customer = models.ForeignKey("accounts.User", on_delete=models.PROTECT, related_name="orders")
status = models.CharField(max_length=20, choices=Status, default=Status.PENDING)
objects = OrderQuerySet.as_manager()
```
## Query performance
- Use `select_related` for forward ForeignKey/OneToOne relations that are read in a loop, and `prefetch_related` (or `Prefetch(...)` with a filtered queryset) for reverse and many-to-many relations.
- Push work to the database: `annotate`, `aggregate`, `exists()`, `count()`, `update()`, `bulk_create()`. Do not iterate in Python to compute totals.
- Bulk operations (`QuerySet.update`, `bulk_create`, queryset `delete`) do not call `save()` and do not send `pre_save`/`post_save` signals. Do not put required business logic only in `save()` or signals if bulk paths exist.
- Lock rows that are read and then updated in the same transaction with `select_for_update()` inside `transaction.atomic()`.
- Profile with `django-debug-toolbar` or `connection.queries` in development. Guard hot views with `assertNumQueries` in tests.
## Signals
- Use signals only to decouple apps that must not import each other, for example reacting to another app's model. For logic inside one app, call a function explicitly; it is easier to find and test.
- Use `transaction.on_commit(...)` for side effects (emails, cache invalidation, enqueuing jobs) that must only happen if the transaction commits.
## Migrations
- Generate a migration for every model change with `makemigrations`, review the generated file, and commit it with the model change. Never edit an applied migration; add a new one.
- In data migrations (`RunPython`), get models with `apps.get_model("app", "Model")`, not direct imports, and provide a reverse function or `migrations.RunPython.noop`.
- In CI, fail when migrations are missing: `python manage.py makemigrations --check --dry-run`.
- On large tables, split schema changes (add nullable column, backfill, then add the constraint) to avoid long locks.
## APIs with Django REST framework (if the project uses it)
- Use `ModelSerializer` with an explicit `fields` list. Never use `fields = "__all__"` on models with sensitive columns.
- Set `permission_classes` on every view or viewset, and paginate list endpoints.
- Apply `select_related`/`prefetch_related` in `get_queryset()` for nested serializers.
## Tests
```python
from django.test import TestCase
from django.urls import reverse
class OrderListTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.user = User.objects.create_user("ana", password="pw") # project user model
def test_requires_login(self):
response = self.client.get(reverse("orders:list"))
self.assertEqual(response.status_code, 302)
def test_query_count_is_constant(self):
self.client.force_login(self.user)
with self.assertNumQueries(3): # set to the measured count for this view
self.client.get(reverse("orders:list"))
```
- Use `setUpTestData` for shared fixtures, `self.client` / `force_login` for request tests, and factories (for example factory_boy) if the project already uses them.
## Verify before finishing
- `python manage.py check`, `python manage.py makemigrations --check --dry-run`, then the project's test command (`python manage.py test` or `pytest` with pytest-django).
- For changed list views, confirm the query count does not grow with the number of rows (N+1 check).
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.
Cursor
backend
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
A Django team asks Cursor to add a paid-orders list page and API without introducing N+1 queries or unreviewed migrations.
Add a 'My paid orders' page at /orders/ that lists each order with customer name and line items (product names). Only logged-in users, only their own orders. Order has customer FK; OrderLine has order FK and product FK. Django 5.2, no DRF.
Illustrative; not a recorded model run. An OrderQuerySet with paid(), for_customer() and with_lines(), using select_related('customer') and prefetch_related('lines__product') and exposed via as_manager(). A ListView with LoginRequiredMixin whose get_queryset() filters to request.user. A URL entry in the app namespace. Tests check the anonymous redirect, that another user's orders are not shown, and use assertNumQueries with a constant count across 1 and 10 orders. No model change means no migration; if a field is added, the answer includes the makemigrations output for review.Cursor applies project rules stored as .mdc files in .cursor/rules. Each rule's frontmatter (description, globs, alwaysApply) decides whether it is always included, attached to matching files, chosen by the agent from its description, or only used when you @-mention it. Cursor also reads AGENTS.md in the project root and subdirectories for plain-Markdown instructions.
.cursor/rules/python-django-patterns.mdcStarting point, not a tested configuration for your repository. Attached when files matching the globs are in context (alwaysApply: false with globs). Review the instructions, adapt the file paths and run your project's existing checks.
---
description: "Python Django Patterns: Views, QuerySets, Migrations, Signals and Tests project conventions"
globs: "**/*"
alwaysApply: false
---
# Django Application Patterns
Applies to: Django projects (views, querysets, migrations, signals, tests and optional Django REST framework APIs). Model field design is covered by a separate model rule.
Version baseline: checked against the Django stable documentation (6.1; 5.2 is the current LTS). Read the pinned Django version in `pyproject.toml` or `requirements*.txt` and follow its documentation if it differs.
## Project structure
- Split code into apps by domain (`orders`, `billing`, `accounts`), not by technical layer. Each app owns its models, migrations, admin, views, urls and tests.
- Keep settings environment-driven: `SECRET_KEY`, database credentials and `DEBUG` come from the environment, never from committed files. Run `python manage.py check --deploy` against production settings.
- Put multi-model business operations in plain functions (for example `orders/services.py`) wrapped in `transaction.atomic()`. Views and serializers stay thin.
## Views
- Use function-based views for one-off logic, and generic class-based views (`ListView`, `DetailView`, `CreateView`, ...) when they remove real boilerplate. Pick one style per app; do not mix both for the same kind of view.
- Fetch single objects with `get_object_or_404`. Enforce permissions in the view (`LoginRequiredMixin`, `PermissionRequiredMixin`, `@login_required`) and also check object ownership. Login alone is not authorization.
- Use Django forms or DRF serializers for input validation. Never trust `request.POST` or `request.data` directly.
## Querysets and managers
Put reusable filters on a custom `QuerySet` and expose it as the manager, so the filters can be chained:
```python
from django.db import models
class OrderQuerySet(models.QuerySet):
def paid(self):
return self.filter(status=Order.Status.PAID)
def for_customer(self, user):
return self.filter(customer=user)
def with_lines(self):
return self.select_related("customer").prefetch_related("lines__product")
class Order(models.Model):
class Status(models.TextChoices):
PENDING = "pending"
PAID = "paid"
customer = models.ForeignKey("accounts.User", on_delete=models.PROTECT, related_name="orders")
status = models.CharField(max_length=20, choices=Status, default=Status.PENDING)
objects = OrderQuerySet.as_manager()
```
## Query performance
- Use `select_related` for forward ForeignKey/OneToOne relations that are read in a loop, and `prefetch_related` (or `Prefetch(...)` with a filtered queryset) for reverse and many-to-many relations.
- Push work to the database: `annotate`, `aggregate`, `exists()`, `count()`, `update()`, `bulk_create()`. Do not iterate in Python to compute totals.
- Bulk operations (`QuerySet.update`, `bulk_create`, queryset `delete`) do not call `save()` and do not send `pre_save`/`post_save` signals. Do not put required business logic only in `save()` or signals if bulk paths exist.
- Lock rows that are read and then updated in the same transaction with `select_for_update()` inside `transaction.atomic()`.
- Profile with `django-debug-toolbar` or `connection.queries` in development. Guard hot views with `assertNumQueries` in tests.
## Signals
- Use signals only to decouple apps that must not import each other, for example reacting to another app's model. For logic inside one app, call a function explicitly; it is easier to find and test.
- Use `transaction.on_commit(...)` for side effects (emails, cache invalidation, enqueuing jobs) that must only happen if the transaction commits.
## Migrations
- Generate a migration for every model change with `makemigrations`, review the generated file, and commit it with the model change. Never edit an applied migration; add a new one.
- In data migrations (`RunPython`), get models with `apps.get_model("app", "Model")`, not direct imports, and provide a reverse function or `migrations.RunPython.noop`.
- In CI, fail when migrations are missing: `python manage.py makemigrations --check --dry-run`.
- On large tables, split schema changes (add nullable column, backfill, then add the constraint) to avoid long locks.
## APIs with Django REST framework (if the project uses it)
- Use `ModelSerializer` with an explicit `fields` list. Never use `fields = "__all__"` on models with sensitive columns.
- Set `permission_classes` on every view or viewset, and paginate list endpoints.
- Apply `select_related`/`prefetch_related` in `get_queryset()` for nested serializers.
## Tests
```python
from django.test import TestCase
from django.urls import reverse
class OrderListTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.user = User.objects.create_user("ana", password="pw") # project user model
def test_requires_login(self):
response = self.client.get(reverse("orders:list"))
self.assertEqual(response.status_code, 302)
def test_query_count_is_constant(self):
self.client.force_login(self.user)
with self.assertNumQueries(3): # set to the measured count for this view
self.client.get(reverse("orders:list"))
```
- Use `setUpTestData` for shared fixtures, `self.client` / `force_login` for request tests, and factories (for example factory_boy) if the project already uses them.
## Verify before finishing
- `python manage.py check`, `python manage.py makemigrations --check --dry-run`, then the project's test command (`python manage.py test` or `pytest` with pytest-django).
- For changed list views, confirm the query count does not grow with the number of rows (N+1 check).
Ask for a small change to one matching file. Check the tool's loaded context or instruction view, inspect the diff for the requested convention, and run the relevant build or test. A well-formatted file does not guarantee the model follows every instruction.
Cursor's docs recommend keeping individual rules under 500 lines and splitting large rules into composable ones. Cursor's documentation states that it supports AGENTS.md in the project root and in subdirectories. Use AGENTS.md for plain-Markdown instructions you also want other tools to read, and .mdc rules when you need Cursor's scoping options (globs, description-based selection, always-apply).
Documentation checked 2026-11-05: Cursor docs: Rules
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.