This document is designed as a security spec that supports:
This document is designed as a security spec that supports:
It is intentionally written as a set of normative requirements (“MUST/SHOULD/MAY”) plus audit rules (what bad patterns look like, how to detect them, and how to fix/mitigate them).
SECRET_KEY, SECRET_KEY_FALLBACKS, database passwords).CsrfViewMiddleware, sprinkling @csrf_exempt, loosening ALLOWED_HOSTS to ['*'], disabling SecurityMiddleware, disabling template auto-escaping, disabling permission checks).When asked to write new Django code or modify existing code:
While working anywhere in a Django repo (even if the user did not ask for a security scan):
When the user asks to “scan”, “audit”, or “hunt for vulns”:
Recommended audit order:
settings.py and environment-specific settings modules.Examples include:
request.GET, request.POST, request.FILESrequest.body, JSON bodies (e.g., json.loads(request.body)), DRF request.data<int:id>, <slug:...>)request.headers / request.META (including HTTP_HOST, HTTP_ORIGIN, HTTP_REFERER, HTTP_X_FORWARDED_*)request.COOKIESDjango explicitly emphasizes “never trust user-controlled data” and recommends using forms/validation. ([Django Project][2])
A request is state-changing if it can create/update/delete data, change auth/session state, trigger side effects (purchase, email send, webhook send), or initiate privileged actions.
For each issue found, output:
This is the smallest “production baseline” that prevents common Django misconfigurations. Django provides a “Deployment checklist” and recommends running manage.py check --deploy against production settings. ([Django Project][1])
SECRET_KEY, DB passwords) and keep them out of source control. Django’s checklist explicitly recommends loading SECRET_KEY from env or a file rather than hardcoding. ([Django Project][1])manage.py runserver as the production entrypoint; use a production-ready WSGI or ASGI server. ([Django Project][1])DEBUG = False in production. ([Django Project][1])SECRET_KEY and keep it secret; MAY use SECRET_KEY_FALLBACKS for safe rotation. ([Django Project][1])ALLOWED_HOSTS to expected hosts (no wildcard unless you do your own host validation). ([Django Project][1])CSRF_COOKIE_SECURE=True and SESSION_COOKIE_SECURE=True when HTTPS is used. ([Django Project][1])SecurityMiddleware headers/settings: HSTS, Referrer-Policy, COOP, nosniff, SSL redirect (with correct proxy configuration). ([Django Project][3])MEDIA_ROOT separate from STATIC_ROOT. ([Django Project][1])Each rule contains: required practice, insecure patterns, detection hints, and remediation.
Severity: High (if production)
Required:
manage.py runserver as the production server.Insecure patterns:
python manage.py runserver 0.0.0.0:8000.CMD/entrypoint uses runserver.runserver.Detection hints:
manage.py runserver, runserver 0.0.0.0, --insecure.CMD/ENTRYPOINT, Procfile, systemd unit files, Helm charts.Fix:
Note:
runserver is fine for local development. Only flag if it’s used as the production entrypoint.DEBUG MUST be disabled in productionSeverity: High
Required:
DEBUG = False in production.DEBUG=True leaks source excerpts, local variables, settings, and more. ([Django Project][1])Insecure patterns:
DEBUG = True in production settings.DEBUG=True unless explicitly overridden.Detection hints:
DEBUG = True, DEBUG=os.environ.get(..., True), DJANGO_DEBUG, .env files.Fix:
DEBUG=False in prod settings; use explicit environment config.SECRET_KEY must be strong, secret, and rotated safelySeverity: High (Critical if missing in production with signing/sessions)
Required:
SECRET_KEY in production and keep it secret. ([Django Project][1])SECRET_KEY_FALLBACKS to avoid instantly invalidating all signed data; MUST remove old keys from fallbacks in a timely manner. ([Django Project][1])Insecure patterns:
SECRET_KEY = "..." in repo for production.SECRET_KEY reused across environments.SECRET_KEY_FALLBACKS contains long-expired keys indefinitely.Detection hints:
SECRET_KEY =, SECRET_KEY_FALLBACKS, .env committed files, print(settings.SECRET_KEY).Fix:
SECRET_KEYSECRET_KEY_FALLBACKSALLOWED_HOSTS must be strict)Severity: Medium
Required:
ALLOWED_HOSTS in production to your expected domains/hosts. ([Django Project][1])ALLOWED_HOSTS = ['*'] in production unless you also implement your own robust Host validation (Django warns that wildcards require your own validation to avoid CSRF-class attacks). ([Django Project][1])Insecure patterns:
ALLOWED_HOSTS = [''] (or env expands to ) in production.ALLOWED_HOSTS = [] with DEBUG=False (site won’t run, or misconfigured deployments attempt workarounds).Detection hints:
ALLOWED_HOSTS.ALLOWED_HOSTS.Fix:
ALLOWED_HOSTS = ['example.com', 'www.example.com', ...] for prod.Notes:
Severity: High (Critical for auth-enabled apps)
NOTE: Only enforce this if TLS is enabled, as it will break non-TLS applications
If using TLS:
CSRF_COOKIE_SECURE = True ([Django Project][1])SESSION_COOKIE_SECURE = True ([Django Project][1])SECURE_SSL_REDIRECT = True (with correct proxy config) ([Django Project][3])SECURE_HSTS_SECONDS (+ includeSubDomains/preload as appropriate). ([Django Project][3])Insecure patterns:
CSRF_COOKIE_SECURE=False or SESSION_COOKIE_SECURE=False in production HTTPS.Detection hints:
settings.py for CSRF_COOKIE_SECURE, SESSION_COOKIE_SECURE, SECURE_SSL_REDIRECT, SECURE_HSTS_SECONDS.Fix:
SECURE_PROXY_SSL_HEADER)Severity: Medium (when behind a TLS proxy)
Required:
request.is_secure() reflects the external scheme, otherwise CSRF and other logic can break. Django documents using SECURE_PROXY_SSL_HEADER for this. ([Django Project][3])SECURE_PROXY_SSL_HEADER if you control the proxy (or have guarantees) and it strips inbound spoofed headers. Django explicitly warns misconfig can compromise security and lists required conditions. ([Django Project][3])Insecure patterns:
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") in an environment where the proxy does not strip user-supplied X-Forwarded-Proto.SECURE_SSL_REDIRECT=True (often indicates proxy HTTPS detection is wrong). ([Django Project][3])Detection hints:
SECURE_PROXY_SSL_HEADER, SECURE_SSL_REDIRECT.Fix:
SECURE_PROXY_SSL_HEADER only if the proxy strips and sets the header correctly (per Django’s documented prerequisites). ([Django Project][3])Severity: Medium (Only if TLS enabled)
Required (production, HTTPS):
SESSION_COOKIE_SECURE=True (only transmit over HTTPS). ([Django Project][3])SESSION_COOKIE_HTTPONLY=True (Django default is True). ([Django Project][3])SESSION_COOKIE_SAMESITE='Lax' (Django default is Lax) unless a justified cross-site flow requires None. ([Django Project][3])SESSION_COOKIE_DOMAIN unless you truly need cross-subdomain cookies (subdomain-wide cookies expand attack surface).Insecure patterns:
SESSION_COOKIE_SECURE=False in production HTTPS.IMPORTANT NOTE: Only set Secure in production environment when TLS is configured. When running in a local dev environment over HTTP, do not set Secure property on cookies. You should do this conditionally based on if the app is running in production mode. You should also include a property like SESSION_COOKIE_SECURE which can be used to disable Secure cookies when testing over HTTP.
SESSION_COOKIE_HTTPONLY=False.SESSION_COOKIE_SAMESITE=None combined with cookie-authenticated state-changing endpoints (higher CSRF risk).Detection hints:
SESSION_COOKIE_ settings, response.set_cookie(..., httponly=..., secure=..., samesite=...).Fix:
Severity: Medium
Required:
CSRF_COOKIE_SECURE=True when using HTTPS/TLS. ([Django Project][3])CSRF_COOKIE_SAMESITE='Lax' unless you have a cross-site requirement. Django default is Lax. ([Django Project][3])CSRF_COOKIE_HTTPONLY=True (default is False) if your frontend does not need to read the CSRF cookie. If you enable it, your JS must read the CSRF token from the DOM instead (Django documents this). ([Django Project][3])Insecure patterns:
CSRF_COOKIE_SECURE=False in production HTTPS/TLS.CSRF_COOKIE_HTTPONLY=True but still relying on “read csrftoken cookie in JS” patterns (breaks CSRF for AJAX).CSRF_COOKIE_SAMESITE=None without a clear reason.Detection hints:
CSRF_COOKIE_ settings.document.cookie usage to fetch csrftoken.Fix:
Severity: High
Required:
django.middleware.csrf.CsrfViewMiddleware enabled (it is activated by default). ([Django Project][4]){% csrf_token %} in internal POST forms; MUST NOT include it in forms that POST to external URLs (Django warns this leaks the token). ([Django Project][4])X-CSRFToken header (or configured header name) as documented. ([Django Project][4])@csrf_exempt and use it only when absolutely necessary; if used, MUST replace CSRF with an appropriate alternative control (e.g., request signing for webhooks). Django explicitly warns about csrf_exempt. ([Django Project][2])Insecure patterns:
CsrfViewMiddleware in MIDDLEWARE.@csrf_exempt on general-purpose authenticated views.Detection hints:
settings.py MIDDLEWARE for CsrfViewMiddleware and its order (Django notes it should come before middleware that assumes CSRF is handled). ([Django Project][4])csrf_exempt, csrf_protect, ensure_csrf_cookie.Fix:
CsrfViewMiddleware, add CSRF tokens to forms, and add AJAX header handling.@csrf_protect as Django documents to avoid caching a response without CSRF cookie/Vary headers. ([Django Project][4])Notes:
Severity: High
Required:
{% autoescape off %}) unless the content is trusted or safely sanitized. ([Django Project][5])mark_safe(...) on user data.|safe on user-controlled content.format_html) rather than manual concatenation that risks missing escapes. ([Django Project][6])Insecure patterns:
{% autoescape off %}{{ user_input }}{% endautoescape %}{{ user_input|safe }}mark_safe(request.GET["q"])<style class={{ var }}>... (Django’s own example). ([Django Project][2])Detection hints:
|safe, autoescape off, safeseq.mark_safe, SafeString, or direct HTML concatenation with request/DB values.HttpResponse(user_value) where user_value contains HTML.Fix:
Severity: High to Critical (depends on context and exposure)
Required:
Insecure patterns:
Template(request.GET["tmpl"]).render(Context(...))Detection hints:
django.template.Template(, Engine.from_string, .render(Context( with non-constant strings.Fix:
string.Template, explicit placeholders) or a strict allowlisted rendering model.Severity: High
Required:
raw(), cursor.execute(), extra(), or RawSQL, MUST pass parameters separately (e.g., params=) and MUST NOT string-interpolate untrusted input into SQL. Django’s raw SQL docs warn to escape user-controlled parameters using params. ([Django Project][7])%s placeholders makes it unsafe). ([Django Project][8])extra() and RawSQL unless necessary; Django security docs call for caution. ([Django Project][2])Insecure patterns:
cursor.execute(f"SELECT ... WHERE id={request.GET['id']}")Model.objects.raw("... %s" % user_input) (string formatting)extra(where=[f"headline='{q}'"])WHERE othercol = '%s' (explicitly documented as unsafe). ([Django Project][8])Detection hints:
.raw(, .extra(, RawSQL(, connection.cursor(), .execute(.SELECT, UPDATE, DELETE, INSERT) in Python strings.Fix:
params, DB-API param binding) and do not quote placeholders. ([Django Project][7])Severity: Critical to High (depends on exposure)
Required:
shell=True with attacker-influenced content.Insecure patterns:
os.system(request.GET["cmd"])subprocess.run(f"convert {path}", shell=True) where path is user-controlled.Detection hints:
os.system, subprocess, Popen, shell=True.Fix:
Severity: High
Required:
.php or HTML to execute/inline as active content). ([Django Project][1])Insecure patterns:
text/html or without forcing download for potentially active formats.Detection hints:
request.FILES, FileField, ImageField, upload forms/views.MEDIA_URL, MEDIA_ROOT, and static config.Fix:
Content-Disposition: attachment for risky types.Severity: High
Required:
MEDIA_ROOT and STATIC_ROOT distinct; Django settings docs explicitly warn they must have different values to avoid security implications. ([Django Project][3])Insecure patterns:
open(os.path.join(MEDIA_ROOT, request.GET["path"]))?file=../../... style parameters.MEDIA_ROOT == STATIC_ROOT.Detection hints:
open(, Path(, os.path.join( used with request values.MEDIA_ROOT, STATIC_ROOT in settings. ([Django Project][3])Fix:
next, return_to, redirect)Severity: Medium (High when combined with auth flows)
Required:
next, return_to).django.utils.http.url_has_allowed_host_and_scheme) rather than custom parsing.Insecure patterns:
return redirect(request.GET.get("next")) with no validation.Detection hints:
redirect( and track origin of the target.next, return_to, redirect, url.Fix:
ALLOWED_HOSTS remains strict (see DJANGO-HOST-001). ([Django Project][3])Severity: Medium to High
Required:
django.middleware.security.SecurityMiddleware and configure it appropriately (production) for:X-Content-Type-Options: nosniff (Django setting SECURE_CONTENT_TYPE_NOSNIFF, default True). ([Django Project][3])Referrer-Policy (Django setting SECURE_REFERRER_POLICY, default 'same-origin'). ([Django Project][3])SECURE_CROSS_ORIGIN_OPENER_POLICY, default 'same-origin'). ([Django Project][3])Insecure patterns:
Detection hints:
MIDDLEWARE for SecurityMiddleware and XFrameOptionsMiddleware.Fix:
NOTE:
Severity: Medium (High for apps rendering untrusted content)
NOTE: It is most important to set the CSP's script-src. All other directives are not as important and can generally be excluded for the ease of development.
Required:
SECURE_CSP_REPORT_ONLY to iterate safely (Django provides report-only support). ([Django Project][3])Insecure patterns:
unsafe-inline) without justification.Detection hints:
SECURE_CSP, SECURE_CSP_REPORT_ONLY, and CSP middleware configuration.Fix:
Severity: High
Required:
PASSWORD_HASHERS and includes modern options (Argon2, bcrypt, scrypt, PBKDF2 variants). ([Django Project][3])AUTH_PASSWORD_VALIDATORS (default is empty) for production password policy. ([Django Project][3])Insecure patterns:
Detection hints:
.set_password( usage vs manual hashing.PASSWORD_HASHERS and AUTH_PASSWORD_VALIDATORS. ([Django Project][3])Fix:
Severity: High
Required:
Insecure patterns:
Detection hints:
is_authenticated or only is_staff without checking object-level access.Fix:
Severity: High
Required:
Insecure patterns:
Detection hints:
urlpatterns for admin.site.urls.Fix:
Severity: Medium to High
Required:
SECRET_KEY, session cookies, auth headers, password reset tokens).DEBUG=False in production so exceptions aren’t rendered with sensitive context. ([Django Project][1])Insecure patterns:
Detection hints:
LOGGING config; search for middleware that logs request headers/cookies.print(settings / logging.info(request.META) patterns.Fix:
Severity: Medium (High if known vulnerable versions)
Required:
Detection hints:
requirements.txt, lockfiles, build images.Fix:
When actively scanning, use these high-signal patterns:
manage.py runserver, runserver 0.0.0.0, --insecure ([Django Project][1])DEBUG = True ([Django Project][1])SECRET_KEY =, SECRET_KEY_FALLBACKS ([Django Project][1])ALLOWED_HOSTS = ['*'] ([Django Project][3])SECURE_SSL_REDIRECT, SECURE_HSTS_SECONDS, SECURE_PROXY_SSL_HEADER ([Django Project][3])SESSION_COOKIE_SECURE, SESSION_COOKIE_HTTPONLY, SESSION_COOKIE_SAMESITE ([Django Project][3])CSRF_COOKIE_SECURE, CSRF_COOKIE_HTTPONLY, CSRF_COOKIE_SAMESITE ([Django Project][3])csrf_exempt, missing CsrfViewMiddleware, POST forms without {% csrf_token %} ([Django Project][4])|safe, autoescape off, mark_safe(, HTML string concatenation ([Django Project][5]).raw(, .extra(, RawSQL(, cursor.execute( with formatted SQL strings ([Django Project][7])request.FILES, MEDIA_ROOT, MEDIA_URL, serving media inline; MEDIA_ROOT == STATIC_ROOT ([Django Project][1])redirect(request.GET.get("next")) patterns; missing allowlist validationSecurityMiddleware, missing X-Frame-Options protection, missing SECURE_CSP adoption (where appropriate) ([Django Project][2])Always try to confirm:
Primary Django documentation:
- Django Downloads (current stable & supported branches): https://www.djangoproject.com/download/
- Django 6.0 Release Notes: https://docs.djangoproject.com/en/6.0/releases/6.0/
- Django: Deployment checklist (incl. check --deploy, runserver warning, HTTPS/cookies guidance): https://docs.djangoproject.com/en/6.0/howto/deployment/checklist/
- Django: Settings reference (SecurityMiddleware settings, cookies, SECRET_KEY_FALLBACKS, CSP settings): https://docs.djangoproject.com/en/6.0/ref/settings/
- Django: Security in Django (XSS/CSRF/SQLi/clickjacking/HTTPS/host header validation/uploads/CSP): https://docs.djangoproject.com/en/6.0/topics/security/
- Django: CSRF how-to (middleware, csrf_token usage, AJAX header patterns, csrf_exempt cautions): https://docs.djangoproject.com/en/6.0/howto/csrf/
- Django: Performing raw SQL queries (parameterization guidance): https://docs.djangoproject.com/en/6.0/topics/db/sql/
- Django: QuerySet API reference (extra() cautions; “do not quote placeholders” guidance): https://docs.djangoproject.com/en/6.0/ref/models/querysets/
- Django: Template built-ins (autoescape tag): https://docs.djangoproject.com/en/6.0/ref/templates/builtins/
- Django: Template language reference (turning off autoescape & risks): https://docs.djangoproject.com/en/6.0/ref/templates/language/
- Django: Utilities reference (e.g., format_html): https://docs.djangoproject.com/en/6.0/ref/utils/
OWASP:
- OWASP Cheat Sheet Series: Django Security Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Django_Security_Cheat_Sheet.html
[1]: https://docs.djangoproject.com/en/6.0/howto/deployment/checklist/ "https://docs.djangoproject.com/en/6.0/howto/deployment/checklist/" [2]: https://docs.djangoproject.com/en/6.0/topics/security/ "Security in Django | Django documentation | Django" [3]: https://docs.djangoproject.com/en/6.0/ref/settings/ "Settings | Django documentation | Django" [4]: https://docs.djangoproject.com/en/6.0/howto/csrf/ "How to use Django’s CSRF protection | Django documentation | Django" [5]: https://docs.djangoproject.com/en/6.0/ref/templates/builtins/ "https://docs.djangoproject.com/en/6.0/ref/templates/builtins/" [6]: https://docs.djangoproject.com/en/6.0/ref/utils/ "https://docs.djangoproject.com/en/6.0/ref/utils/" [7]: https://docs.djangoproject.com/en/6.0/topics/db/sql/ "https://docs.djangoproject.com/en/6.0/topics/db/sql/" [8]: https://docs.djangoproject.com/en/6.0/ref/models/querysets/ "https://docs.djangoproject.com/en/6.0/ref/models/querysets/" [9]: https://www.djangoproject.com/download/ "Download Django | Django"