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

# Building HttpRequest and QueryDict

How do `WSGIRequest` and `ASGIRequest` decode headers, cookies, and query strings lazily, and why is `QueryDict` immutable by default?

Every view receives a single **`HttpRequest`** object (`django/http/request.py:HttpRequest`) that appears to hold fully parsed dictionaries for query parameters, form fields, cookies, and headers. Yet constructing a request on every incoming HTTP hit would waste substantial CPU if Django parsed query strings, split cookie headers, and decoded form bodies on endpoints that never touch them.

Open `WSGIRequest.__init__` (`django/core/handlers/wsgi.py:WSGIRequest.__init__`) and `ASGIRequest.__init__` (`django/core/handlers/asgi.py:ASGIRequest.__init__`), and you see the opposite strategy: both subclasses skip `HttpRequest.__init__` entirely (there is an explicit warning comment on line 63 of `django/http/request.py`) and leave almost every dictionary unparsed until application code first touches it.

## Lazy descriptors on `WSGIRequest` and `ASGIRequest`

At construction time, `WSGIRequest.__init__` does only the bare minimum needed for routing: it extracts `path_info`, `path`, `method`, `"CONTENT_TYPE"` parameters (encoding), and wraps `"wsgi.input"` inside `LimitedStream` (`django/core/handlers/wsgi.py:LimitedStream`). Everything else waits behind `@cached_property` or custom properties:

- `WSGIRequest.GET` (`django/core/handlers/wsgi.py:WSGIRequest.GET`) and `ASGIRequest.GET` (`django/core/handlers/asgi.py:ASGIRequest.GET`) parse `"QUERY_STRING"` into a `QueryDict` only on first read, then cache the result straight into the instance's `__dict__`.
- `WSGIRequest.COOKIES` (`django/core/handlers/wsgi.py:WSGIRequest.COOKIES`) and `ASGIRequest.COOKIES` (`django/core/handlers/asgi.py:ASGIRequest.COOKIES`) run `parse_cookie` only on first read.
- `HttpRequest.headers` (`django/http/request.py:HttpRequest.headers`) constructs an **`HttpHeaders`** wrapper (`django/http/request.py:HttpHeaders`) lazily on first read. `HttpHeaders` subclasses `CaseInsensitiveMapping` (`django/utils/datastructures.py:CaseInsensitiveMapping`), scanning `META` once for keys starting with `"HTTP_"` plus the two unprefixed CGI headers (`"CONTENT_TYPE"` and `"CONTENT_LENGTH"`), stripping `"HTTP_"`, turning underscores into title-cased hyphens (`"HTTP_X_DESK_TOKEN"` → `"X-Desk-Token"`), and normalizing underscores to hyphens inside `HttpHeaders.__getitem__` so both `"x-desk-token"` and `"X_DESK_TOKEN"` resolve identically.
- `POST` and `FILES` check `hasattr(self, "_post")` / `hasattr(self, "_files")` and call `HttpRequest._load_post_and_files` (`django/http/request.py:HttpRequest._load_post_and_files`) only when touched.

Watch every one of those lazy structures populate on demand in a live trace on Django `6.1.3`:

```text recording=ch04-routing
WSGIRequest lazy parsing, HttpHeaders, QueryDict, and RawPostDataException
  before access: 'GET' in __dict__=False 'COOKIES' in __dict__=False 'headers' in __dict__=False '_post' in __dict__=False
  after access:  'GET' in __dict__=True 'COOKIES' in __dict__=True 'headers' in __dict__=True
  HttpHeaders case/underscore fold: headers['x-desk-token']='press-42' headers['X_DESK_TOKEN']='press-42' cookies={'desk_edition': 'morning', 'theme': 'print'}
  QueryDict multi-value: qd['tag']='council' qd.getlist('tag')=['metro', 'budget', 'council']
  mutating request.GET -> AttributeError: This QueryDict instance is immutable
  after qd.copy(): _mutable=True copy.getlist('tag')=['metro', 'budget', 'council', 'sports'] original=['metro', 'budget', 'council']
  6 fields with limit=5 -> TooManyFieldsSent: The number of GET/POST parameters exceeded settings.DATA_UPLOAD_MAX_NUMBER_FIELDS.
  urlencoded POST then body -> ok len(body)=31 headline='Bridge vote'
  multipart POST then body -> RawPostDataException: You cannot access body after reading from request's data stream
  multipart body then POST -> ok len(body)=110 headline='Bridge vote'
```

## Inside `QueryDict`: multi-value storage and immutability

HTTP query strings and HTML `<select multiple>` forms routinely repeat the same parameter name (`"tag=metro&tag=budget&tag=council"`). A plain Python `dict` would silently discard earlier values, so Django parses both `GET` and `POST` into **`QueryDict`** (`django/http/request.py:QueryDict`), a subclass of `MultiValueDict` (`django/utils/datastructures.py:MultiValueDict`).

Internally, `MultiValueDict` stores a Python `list` for *every* key (`{"tag": ["metro", "budget", "council"]}`). Indexing `qd["tag"]` calls `MultiValueDict.__getitem__`, which returns `list_[-1]` — the **last** value (`"council"`), matching browser and CGI conventions — while `MultiValueDict.getlist` returns the full list `["metro", "budget", "council"]`.

At the end of `QueryDict.__init__`, Django sets `self._mutable = mutable` — defaulting to **`False`** for every request's `GET` and `POST`. Every mutating method (`__setitem__`, `__delitem__`, `setlist`, `appendlist`, `pop`, `clear`, `setdefault`) begins by calling `QueryDict._assert_mutable`, which raises `AttributeError("This QueryDict instance is immutable")`.

> **Why.** `HttpRequest` passes through eight middleware layers, view decorators, form constructors, and template context processors during one request. If middleware or a form helper mutated `GET` or `POST` in place to inject a default filter or normalize a field, downstream code (or `ExceptionReporter` logging a traceback) would see fabricated input instead of what the client sent. Calling `QueryDict.copy` performs a deep copy and returns a new `QueryDict` with `_mutable = True`, leaving the original untouched.

Notice line 606 of `django/http/request.py` as well: `QueryDict.__init__` passes `max_num_fields=settings.DATA_UPLOAD_MAX_NUMBER_FIELDS` (default `1,000`) directly to `urllib.parse.parse_qsl`. If an attacker sends a form or query string with `1,001` keys to provoke CPU or memory exhaustion, `QueryDict` catches the resulting `ValueError` and translates it into `TooManyFieldsSent` (`django/core/exceptions.py:TooManyFieldsSent`), which Chapter 3's `response_for_exception` turns into a `400 Bad Request` logged to `"django.security.TooManyFieldsSent"`.

## The `RawPostDataException` asymmetry

Look at the last three lines of our recording above, because they expose a nuance almost every developer misremembers.

You are often told: *"Never read `HttpRequest.body` after `POST`, or Django raises `RawPostDataException`."* Yet on our `"application/x-www-form-urlencoded"` POST, reading `POST` *and then* reading `HttpRequest.body` succeeded cleanly! Only the `"multipart/form-data"` POST crashed with `RawPostDataException` (`django/http/request.py:RawPostDataException`).

Open lines 462–487 of `django/http/request.py` to see why:

- For `"application/x-www-form-urlencoded"`, line 486 runs `self._post = QueryDict(self.body, encoding="utf-8")`. Reading `POST` internally accesses `HttpRequest.body` (`django/http/request.py:HttpRequest.body`), which checks `settings.DATA_UPLOAD_MAX_MEMORY_SIZE`, reads the raw stream once into `HttpRequest._body`, closes the raw socket stream, and swaps `self._stream = io.BytesIO(self._body)`. Subsequent reads of `HttpRequest.body` simply return the cached bytes.
- For `"multipart/form-data"`, line 467 deliberately does **not** load the entire upload into `HttpRequest._body` — that would pull a `200 MiB` file upload straight into RAM! Instead, if `_body` has not been populated yet, it hands `self` directly to `HttpRequest.parse_file_upload`, which streams chunks via `HttpRequest.read`, flipping `_read_started = True` without creating `_body`. If later code asks for `HttpRequest.body`, line 402 sees `not hasattr(self, "_body")` and `self._read_started == True`, and raises `RawPostDataException`.
- Conversely, if middleware reads `HttpRequest.body` *first* on a small multipart upload, line 463 sees `hasattr(self, "_body")` and feeds `io.BytesIO(self._body)` into the multipart parser — so both `body` and `POST` succeed, at the cost of buffering the full multipart payload in memory (up to `DATA_UPLOAD_MAX_MEMORY_SIZE`).

## Where `HttpRequest` leaks

- **Reading `HttpRequest.body` in logging or signature-verification middleware defeats streaming uploads.** Touching `HttpRequest.body` on a multipart upload forces the entire body into memory and trips `RequestDataTooBig` once it exceeds `DATA_UPLOAD_MAX_MEMORY_SIZE` (`2.5 MiB` default), even when a view expects `100 MiB` file uploads streamed to disk.
- **Changing `HttpRequest.encoding` invalidates cached `GET` and `POST`.** Look at `HttpRequest.encoding` (`django/http/request.py:HttpRequest.encoding`): assigning a new encoding deletes both `GET` and `_post` so they re-decode lazily on next access — but only if you have not already consumed a multipart stream.
- **Reaching into `META` skips `HttpHeaders` normalization.** Reading `"HTTP_X_DESK_TOKEN"` directly works, but `"CONTENT_TYPE"` and `"CONTENT_LENGTH"` lack the `"HTTP_"` prefix in WSGI and ASGI `META`, whereas `HttpRequest.headers` handles all headers uniformly and case-insensitively.

That multipart streaming path leads straight into how Django handles uploaded files without exhausting RAM — and what flips upside down when a view streams its response back out — in [File uploads and streaming responses](uploads-and-streaming.md).
