---
django: 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a)
---

# 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** | `DisallowedHost` (when `get_host()` runs), `"nosniff"`, `Referrer-Policy`, `"COOP"` | `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** | `CsrfViewMiddleware` on all unsafe methods | Views mutating state on `GET`; careless `@csrf_exempt` on cookie-authenticated endpoints. |
| **HTML injection (XSS)** | Autoescaping in DjangoTemplates, `format_html` 0-arg `TypeError` | `mark_safe` / `\|safe`, `href="javascript:..."`, unquoted attributes, inline `<script>` / `<style>`. |
| **SQL injection** | Parameterized SQL inside the ORM (`QuerySet`, `Q`, `F`) | f-strings or `%` formatting in `RawSQL`, `QuerySet.raw`, `QuerySet.extra`, or raw cursor execution. |
| **Mass assignment** | Nothing — `ModelForm` binds whatever `"Meta.fields"` lists | `fields = "__all__"` or omitting `"status"` / `"is_staff"` from `exclude` lets attackers overwrite privileged columns. |
| **Authorisation (IDOR)** | `login_required` / `permission_required` check *who* you are or model-level permissions | **Object-level authorisation:** checking that reporter A owns draft story #42 before editing or viewing it. |
| **Debug & secrets** | `SafeExceptionReporterFilter` scrubs common key names when `DEBUG = False` | 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.

```text recording=ch05-security
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` (`django/middleware/csrf.py: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:

- **Broken object-level authorisation (IDOR):** Django's `AuthenticationMiddleware` verifies *who* sent the request, and `PermissionRequiredMixin` checks whether that user holds a model-level permission like `"newsroom.change_story"`. Neither checks whether the logged-in reporter is allowed to edit **this specific** story row (`pk=42`) owned by a different desk! Every detail, edit, and delete view must scope its queryset to the caller (for example filtering by `reporter=request.user` or checking an explicit ownership predicate inside `get_queryset`) — never fetch `"Story.objects.get(pk=pk)"` unfiltered and trust that the URL came from a link the user was allowed to see.
- **Unsafe SQL interpolation:** Django's ORM separates SQL structure from bound parameters automatically (`WHERE slug = %s` with `params=["..."]`, Chapter 8). The moment application code interpolates user input into `RawSQL` (`django/db/models/expressions.py:RawSQL`), `QuerySet.raw` (`django/db/models/query.py:QuerySet.raw`), `QuerySet.extra`, or `CursorWrapper.execute` (`django/db/backends/utils.py:CursorWrapper.execute`) via f-strings or `%` formatting, Django passes that string straight to the database driver. Whenever raw SQL is genuinely required, pass user values exclusively through the `params` argument 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](../models.md).
