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_, SECURE_, SESSION_, CSRF_ default to False! Edge proxy must strip X-Forwarded-Proto. |
| Cross-site forgery | What Django enforces by default Csrf 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_ 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 Safe 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:// without TLS certificates! Django ships a built-in deployment audit (manage, 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.
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:
- 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). Swap that single line to.Status .DRAFT" fields = "__all__"— a shortcut both hurried humans and AI code generators reach for constantly — and the exact same POST body passesis_valid()and promotes a draft straight to"published"without passing an editor! Always declare an explicitfields = [...]allow-list on everyModelForm. - Short-circuit middleware placed above
SecurityMiddleware: Remember Chapter 3’s middleware onion (BaseHandler). When a rate-limiter or IP-block middleware returns.load_middleware HttpResponse(status=429)before callingget_response, the request never descends into layers below it — and therefore those inner layers’ response hooks never run. Putting the rate-limiter aboveSecurityMiddlewareemits a429missing bothX-Content-Type-Options: nosniffandX-Frame-Options: DENY; placing it belowSecurityMiddlewareandXFrameOptionsMiddlewarelets both outer shields wrap even short-circuited error responses! - Middleware dependency crashes: Enable
CSRF_USE_SESSIONS = TruewithCsrfViewMiddlewarelisted aboveSessionMiddlewareandCsrfViewMiddlewareraises._get_secret ImproperlyConfiguredat request time because"requesthas not been attached yet..session"
Authorisation and raw SQL: the two bugs Django cannot catch
Two high-severity vulnerabilities sit permanently outside any framework-wide middleware:
- Broken object-level authorisation (IDOR): Django’s
AuthenticationMiddlewareverifies who sent the request, andPermissionRequiredMixinchecks whether that user holds a model-level permission like"newsroom. Neither checks whether the logged-in reporter is allowed to edit this specific story row (.change_story" pk=42) owned by a different desk! Every detail, edit, and delete view must scope its queryset to the caller (for example filtering byreporter=requestor checking an explicit ownership predicate inside.user get_queryset) — never fetch"Storyunfiltered and trust that the URL came from a link the user was allowed to see..objects .get(pk=pk)" - Unsafe SQL interpolation: Django’s ORM separates SQL structure from bound parameters automatically (
WHERE slug = %swithparams=["..."], Chapter 8). The moment application code interpolates user input intoRawSQL,QuerySet.raw,QuerySet.extra, orCursorWrappervia f-strings or.execute %formatting, Django passes that string straight to the database driver. Whenever raw SQL is genuinely required, pass user values exclusively through theparamsargument so the database driver binds them outside the SQL grammar.
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.