Django 6.1.3

5.6 Security by default

Where Django’s defaults stop protecting you

Which real vulnerabilities — authorisation, mass assignment, unsafe raw SQL, misordered middleware — sit entirely outside Django’s built-in shields?

After tracing SecurityMiddleware, CommonMiddleware, CsrfViewMiddleware, Signer, ContentSecurityPolicyMiddleware, XFrameOptionsMiddleware, and SafeString, it is tempting to assume that a default Django project is safe unless you explicitly turn something off.

That assumption is where real production incidents begin. Every shield in this chapter operates at the protocol or syntax layer — HTTP headers, request origin, cryptographic integrity, HTML entity encoding. None of them understand your application’s business rules. Knowing the exact trust boundary — where Django’s framework guarantees end and your view, form, query, and deployment code take over — matters just as much as knowing the middleware internals.

The trust boundary map

Threat class What Django enforces by default Where the trust boundary hands off to you
Host & transport What Django enforces by default DisallowedHost (when get_host() runs), "nosniff", Referrer-Policy, "COOP" Where the trust boundary hands off to you SECURE_SSL_REDIRECT, SECURE_HSTS_SECONDS, SESSION_COOKIE_SECURE, CSRF_COOKIE_SECURE default to False! Edge proxy must strip X-Forwarded-Proto.
Cross-site forgery What Django enforces by default CsrfViewMiddleware on all unsafe methods Where the trust boundary hands off to you Views mutating state on GET; careless @csrf_exempt on cookie-authenticated endpoints.
HTML injection (XSS) What Django enforces by default Autoescaping in DjangoTemplates, format_html 0-arg TypeError Where the trust boundary hands off to you mark_safe / |safe, href="javascript:...", unquoted attributes, inline <script> / <style>.
SQL injection What Django enforces by default Parameterized SQL inside the ORM (QuerySet, Q, F) Where the trust boundary hands off to you f-strings or % formatting in RawSQL, QuerySet.raw, QuerySet.extra, or raw cursor execution.
Mass assignment What Django enforces by default Nothing — ModelForm binds whatever "Meta.fields" lists Where the trust boundary hands off to you fields = "__all__" or omitting "status" / "is_staff" from exclude lets attackers overwrite privileged columns.
Authorisation (IDOR) What Django enforces by default login_required / permission_required check who you are or model-level permissions Where the trust boundary hands off to you Object-level authorisation: checking that reporter A owns draft story #42 before editing or viewing it.
Debug & secrets What Django enforces by default SafeExceptionReporterFilter scrubs common key names when DEBUG = False Where the trust boundary hands off to you Deploying with DEBUG = True (leaks locals, SQL, POST values, tracebacks); custom secret names outside hidden_settings.

Look closely at row 1 of that table: transport security settings default to False (SECURE_SSL_REDIRECT, SECURE_HSTS_SECONDS, SESSION_COOKIE_SECURE, CSRF_COOKIE_SECURE) so "runserver" works on http://127.0.0.1:8000 without TLS certificates! Django ships a built-in deployment audit (manage.py check --deploy, Chapter 13) specifically to flag those unset production flags — yet nothing stops you from deploying with all four still False.

Two live failures on our newsroom app

To make the trust boundary tangible rather than abstract, run two real failure modes directly against our newsroom app on Django 6.1.3: mass assignment via ModelForm and misordered middleware dropping security headers or crashing CSRF.

Recorded on Django 6.1.3 ch05-security script
Where Django defaults stop: mass assignment and misordered middleware
  StoryForm (explicit fields): is_valid=True status=Story.Status.DRAFT (crafted 'published' ignored)
  UnsafeStoryForm (fields='__all__'): is_valid=True status='published' (MASS ASSIGNMENT!)
  429 short-circuit ABOVE SecurityMiddleware -> 429 Too Many Requests nosniff=None XFO=None
  429 short-circuit BELOW SecurityMiddleware -> 429 Too Many Requests nosniff='nosniff' XFO='DENY'
  CSRF_USE_SESSIONS with Csrf before Session -> ImproperlyConfigured: CSRF_USE_SESSIONS is enabled, but request.session is not set. SessionMiddleware must appear before CsrfViewMiddleware in MIDDLEWARE.

Examine all three proofs in that trace:

  1. Mass assignment (ModelForm): Our newsroom’s StoryForm declares an explicit allow-list (fields = ["headline", "slug", "desk", "reporter", "edition", "priority", "body"]), intentionally omitting "status". When an untrusted POST injects "status": "published", StoryForm silently ignores the extra POST key and keeps the story in draft ("Story.Status.DRAFT"). Swap that single line to fields = "__all__" — a shortcut both hurried humans and AI code generators reach for constantly — and the exact same POST body passes is_valid() and promotes a draft straight to "published" without passing an editor! Always declare an explicit fields = [...] allow-list on every ModelForm.
  2. Short-circuit middleware placed above SecurityMiddleware: Remember Chapter 3’s middleware onion (BaseHandler.load_middleware). When a rate-limiter or IP-block middleware returns HttpResponse(status=429) before calling get_response, the request never descends into layers below it — and therefore those inner layers’ response hooks never run. Putting the rate-limiter above SecurityMiddleware emits a 429 missing both X-Content-Type-Options: nosniff and X-Frame-Options: DENY; placing it below SecurityMiddleware and XFrameOptionsMiddleware lets both outer shields wrap even short-circuited error responses!
  3. Middleware dependency crashes: Enable CSRF_USE_SESSIONS = True with CsrfViewMiddleware listed above SessionMiddleware and CsrfViewMiddleware._get_secret raises ImproperlyConfigured at request time because "request.session" has not been attached yet.

Authorisation and raw SQL: the two bugs Django cannot catch

Two high-severity vulnerabilities sit permanently outside any framework-wide middleware:

Closing Part I: from HTTP bytes to Python models

We have now followed a single HTTP request all the way across Part I: from process startup and lazy settings (Chapter 2), through WSGI/ASGI entry and the sync/async middleware onion (Chapter 3), through lazy request parsing, URL compilation, decorators, CBVs, and response teardown (Chapter 4), and finally through every built-in security barrier and the trust boundary where Django’s defaults stop (Chapter 5).

At this point in a real request, the request is validated, routed, authorized, and standing inside a view — and almost every view’s very first line talks to the database. We turn now to Part II, The ORM, starting with how a Python class becomes a database table in Models, metaclasses, and state.