AGENTS.md — Django
- Follow PEP 8; format with black (88-char code lines, 79 for docs/comments). 4-space Python indent, 2-space HTML.
underscore_casefor variables/functions/methods,InitialCapsfor classes. Views takerequestas the first arg.- Sort imports with isort: future → stdlib → third-party → other Django → local → try/except. Absolute for Django, one-dot relative for local.
- Don't use f-strings for translatable strings; mark strings for i18n and use
format(). - Models: lowercase underscore field names;
class Metaafter fields; order is fields → managers → Meta →__str__→save()→get_absolute_url()→ custom methods. - Avoid N+1:
select_related()for FK/OneToOne,prefetch_related()for ManyToMany and reverse relations. - QuerySets are lazy and cache once evaluated — store and reuse them; don't re-query in loops.
- Prefer
update(),bulk_create(),bulk_update(),F()expressions, andannotate()over per-objectsave()loops. Usevalues()/only()to fetch less. - Use the ORM for SQL safety; use
raw()/extra()/RawSQL()sparingly and escape user input. - Never disable CSRF (
{% csrf_token %}+CsrfViewMiddleware); avoid@csrf_exemptunless required. - Let template auto-escaping handle XSS; be careful with
mark_safe/safe/autoescape-off and stored HTML. - Set
ALLOWED_HOSTS; read host viarequest.get_host(), notrequest.META. - Production:
DEBUG = False, secretSECRET_KEY, HTTPS withSECURE_SSL_REDIRECT, secure cookies, and HSTS. - Keep clickjacking (
X-Frame-Options) protection on; validate input through forms; limit upload sizes. - Never read
django.conf.settingsat module import time — use lazy indirection (LazyObject,lazy(),lambda). - Add
Meta.indexes/db_indexfor frequently filtered fields; profile withQuerySet.explain()before optimizing.