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

# One request from wire to HTML

What actually wakes up inside Django between a web server handing over a request dictionary and receiving back HTML bytes?

Take the Wednesday edition front of our newsroom project at `"/editions/2026-11-25/"`. Suppose someone writes the shortest idiomatic generic `ListView` (`django/views/generic/list.py:ListView`) that satisfies the specification: fetch the edition matching the URL slug, return its published stories, and render the edition template.

```python
class NaiveEditionListView(ListView):
    model = Story
    template_name = "newsroom/edition.html"
    context_object_name = "stories"

    def get_queryset(self):
        self.edition = get_object_or_404(Edition, slug=self.kwargs["issue_date"])
        return Story.objects.filter(edition=self.edition, status=Story.Status.PUBLISHED)
```

The template (`"newsroom/edition.html"`) loops over the stories context variable and prints each story's headline, desk name, reporter name, and — if the story has any corrections — how many:

```django
{% for story in stories %}
  <li>
    <a href="{% url 'story-detail' slug=story.slug %}">{{ story.headline }}</a>
    <span class="byline">{{ story.desk.name }} · {{ story.reporter.name }}</span>
    {% if story.corrections.all %}
      <span class="corrections">({{ story.corrections.all|length }} correction{{ story.corrections.all|length|pluralize }})</span>
    {% endif %}
  </li>
{% endfor %}
```

The Wednesday edition holds **four published stories**, two of which have corrections. Before looking at the recording below, make an honest guess: how many SQL queries does this view run, and when in the call stack do they fire?

Most experienced Django engineers count carefully and answer **fourteen**: one query for the edition, one for the four stories, four for each story's desk, four for each reporter, and four for each story's corrections (`1 + 1 + 4 + 4 + 4 = 14`).

## The machine's answer

Run that exact view against Django `6.1.3` and the answer is not fourteen. It is **eighteen** (`django/template/response.py:SimpleTemplateResponse.render`, `django/template/base.py:Template.render`).

```text recording=ch01-one-request
Naive view on 4 stories (2026-11-25): 17 of 18 queries fire inside Template.render
  NaiveEditionListView.dispatch(issue_date='2026-11-25')
    NaiveEditionListView.get_queryset
      SQL SELECT "newsroom_edition"."id", "newsroom_edition"."issue_date", "newsroom_edition"."slug", "newsroom_edition"."title", "newsroom_edition"."status", "newsroom_edition"."published_at" FROM "newsroom_edition" WHERE "newsroom_edition"."slug" = %s LIMIT 21  params=('2026-11-25',)
    NaiveEditionListView.render_to_response -> TemplateResponse (unrendered)
  TemplateResponse.render(template=['newsroom/edition.html', 'newsroom/story_list.html'])
    Template.render('newsroom/edition.html')
      SQL SELECT "newsroom_story"."id", "newsroom_story"."headline", "newsroom_story"."slug", "newsroom_story"."body", "newsroom_story"."priority", "newsroom_story"."status", "newsroom_story"."published_at", "newsroom_story"."desk_id", "newsroom_story"."reporter_id", "newsroom_story"."edition_id" FROM "newsroom_story" WHERE ("newsroom_story"."edition_id" = %s AND "newsroom_story"."status" = %s) ORDER BY "newsroom_story"."priority" ASC, "newsroom_story"."id" ASC  params=(2, Story.Status.PUBLISHED)
      SQL SELECT "newsroom_desk"."id", "newsroom_desk"."name", "newsroom_desk"."slug", "newsroom_desk"."section_code" FROM "newsroom_desk" WHERE "newsroom_desk"."id" = %s LIMIT 21  params=(1,)
      SQL SELECT "newsroom_reporter"."id", "newsroom_reporter"."name", "newsroom_reporter"."email", "newsroom_reporter"."desk_id", "newsroom_reporter"."user_id" FROM "newsroom_reporter" WHERE "newsroom_reporter"."id" = %s LIMIT 21  params=(1,)
      SQL SELECT "newsroom_correction"."id", "newsroom_correction"."story_id", "newsroom_correction"."note", "newsroom_correction"."issued_at" FROM "newsroom_correction" WHERE "newsroom_correction"."story_id" = %s ORDER BY "newsroom_correction"."issued_at" ASC, "newsroom_correction"."id" ASC  params=(1,)
      SQL SELECT "newsroom_correction"."id", "newsroom_correction"."story_id", "newsroom_correction"."note", "newsroom_correction"."issued_at" FROM "newsroom_correction" WHERE "newsroom_correction"."story_id" = %s ORDER BY "newsroom_correction"."issued_at" ASC, "newsroom_correction"."id" ASC  params=(1,)
      SQL SELECT "newsroom_correction"."id", "newsroom_correction"."story_id", "newsroom_correction"."note", "newsroom_correction"."issued_at" FROM "newsroom_correction" WHERE "newsroom_correction"."story_id" = %s ORDER BY "newsroom_correction"."issued_at" ASC, "newsroom_correction"."id" ASC  params=(1,)
...
  TRAP naive 4-story run: queries=18  html_bytes=1219  identical_html=True
```

Look at those three identical lines in the middle of the trace, all with `params=(1,)`. Why did story #1 query the corrections table three times in a row?

Because the template wrote `"story.corrections.all"` three times. Without prefetching, every evaluation of `"story.corrections.all"` calls `QuerySet.all` via the related manager and constructs a *fresh, uncached* `QuerySet`. The `{% if story.corrections.all %}` branch runs the first SELECT to check truthiness; finding two rows, the template enters the `if` block and runs a *second* SELECT to compute `|length`, and then a *third* SELECT to feed `|length|pluralize`! On the two stories that have corrections, each story fires three identical queries instead of one — adding four unexpected queries on top of the fourteen you predicted.

On four stories in local development, eighteen queries take `6.52 milliseconds`, so nobody notices. Now put a two-hundred-story Sunday edition behind that exact same view and compare it against the real view in our newsroom project, which chains `QuerySet.select_related` (for desk and reporter) and `QuerySet.prefetch_related` (for corrections) onto `get_queryset`.

```text recording=ch01-one-request
Naive vs. eager view: 4 stories vs. 200 stories (query counts and byte parity)
  view              stories   in_view   in_template   total_sql   html_bytes
  naive                   4         1            17           18         1219
  eager                   4         1             2            3         1219
  TRAP naive            200         1           641          642        36394
  eager                 200         1             2            3        36394
  identical_html_4=True  identical_html_200=True
```

```text recording=ch01-bench
Measured request time: naive vs. eager view (median of 7 warm runs, in-memory SQLite)
  view       stories   sql   view_ms   render_ms   total_ms   least_ms
  naive            4    18      0.41        6.12       6.52       6.45
  eager            4     3      0.44        1.66       2.10       2.07
  TRAP naive     200   642      0.43      208.54     208.98     204.69
  eager          200     3      0.52       19.12      19.65      19.50
  at 200 stories (zero network latency): naive is 10.6x slower than eager; 99.8% of naive time spent inside TemplateResponse.render
```

Both views return `36,394` identical bytes of HTML. Yet even against an in-memory SQLite database where network latency is literally zero, the naive view runs `642` SQL queries and spends `208.98 ms` — `10.6x` slower than the eager view's `19.65 ms`. Over a real PostgreSQL connection at half a millisecond per round-trip, those `639` extra queries add a third of a second of pure network wait before the database parses a single row.

And look again at the view-time column (`"view_ms"`): `0.43 ms` out of `208.98 ms`. To understand *how* `99.8%` of a view's work happens after the view function has already returned, we need to trace the whole request from the WSGI server dictionary to the moment the response closes.

## The whole WSGI lifecycle on one page

Here is the real newsroom view (`GET /editions/2026-11-25/`) executed end to end through `WSGIHandler`, with every framework boundary and SQL statement recorded in the exact order Django runs it (`django/core/handlers/wsgi.py:WSGIHandler.__call__`).

```text recording=ch01-one-request
WSGIHandler: GET /editions/2026-11-25/ through desk/
  WSGIHandler.__call__(PATH_INFO='/editions/2026-11-25/')
    signal request_started (sender=WSGIHandler)
    WSGIRequest.__init__(GET /editions/2026-11-25/)
    BaseHandler.get_response
      TimingHeaderMiddleware.__call__
        BaseHandler._get_response
          URLResolver.resolve('/editions/2026-11-25/')
            URLResolver.resolve('editions/2026-11-25/')
          EditionListView.dispatch(issue_date='2026-11-25')
            EditionListView.get_queryset
              SQL SELECT "newsroom_edition"."id", "newsroom_edition"."issue_date", "newsroom_edition"."slug", "newsroom_edition"."title", "newsroom_edition"."status", "newsroom_edition"."published_at" FROM "newsroom_edition" WHERE "newsroom_edition"."slug" = %s LIMIT 21  params=('2026-11-25',)
            EditionListView.render_to_response -> TemplateResponse (unrendered)
          TemplateResponse.render(template=['newsroom/edition.html', 'newsroom/story_list.html'])
            Template.render('newsroom/edition.html')
              SQL SELECT "newsroom_story"."id", "newsroom_story"."headline", "newsroom_story"."slug", "newsroom_story"."body", "newsroom_story"."priority", "newsroom_story"."status", "newsroom_story"."published_at", "newsroom_story"."desk_id", "newsroom_story"."reporter_id", "newsroom_story"."edition_id", "newsroom_desk"."id", "newsroom_desk"."name", "newsroom_desk"."slug", "newsroom_desk"."section_code", "newsroom_reporter"."id", "newsroom_reporter"."name", "newsroom_reporter"."email", "newsroom_reporter"."desk_id", "newsroom_reporter"."user_id" FROM "newsroom_story" INNER JOIN "newsroom_desk" ON ("newsroom_story"."desk_id" = "newsroom_desk"."id") INNER JOIN "newsroom_reporter" ON ("newsroom_story"."reporter_id" = "newsroom_reporter"."id") WHERE ("newsroom_story"."edition_id" = %s AND "newsroom_story"."status" = %s) ORDER BY "newsroom_story"."priority" ASC, "newsroom_story"."id" ASC  params=(2, Story.Status.PUBLISHED)
              SQL SELECT "newsroom_correction"."id", "newsroom_correction"."story_id", "newsroom_correction"."note", "newsroom_correction"."issued_at" FROM "newsroom_correction" WHERE "newsroom_correction"."story_id" IN (%s, %s, %s, %s) ORDER BY "newsroom_correction"."issued_at" ASC, "newsroom_correction"."id" ASC  params=(1, 3, 2, 4)
    start_response('200 OK', headers=[Content-Type, X-Frame-Options, Content-Length, X-Desk-Ms, X-Content-Type-Options, Referrer-Policy, Cross-Origin-Opener-Policy])
  HttpResponseBase.close
    signal request_finished (sender=WSGIHandler)
  done: status='200 OK'  queries=3  html_bytes=1219  has_x_desk_ms=True
```

```text figure=request-lifecycle
GET /editions/2026-11-25/ through Django 6.1.3 WSGIHandler (3 SQL queries, 1,219 HTML bytes, 2.10 ms, 200 OK)

Part I · Entry, middleware, routing
  WSGI Server (environ, start_response) -> WSGIHandler.__call__ (signal request_started, WSGIRequest)
  -> Middleware onion (8 layers: Security, Timing, Session, Common, Csrf, Auth, Message, XFrameOptions)
  -> URLResolver.resolve('/editions/2026-11-25/') -> BaseHandler._get_response

View phase (0.44 ms)
  EditionListView.dispatch -> get_queryset
  -> SQL #1 eager lookup: FROM newsroom_edition WHERE slug = %s LIMIT 21
  -> returns unrendered TemplateResponse (0 story rows fetched)

Deferred render phase (1.66 ms · ORM + templates)
  TemplateResponse.render -> Template.render('newsroom/edition.html')
  -> {% for story in stories %} triggers QuerySet._fetch_all
  -> SQL #2: Story JOIN Desk JOIN Reporter (4 rows)
  -> SQL #3: Correction WHERE story_id IN (1, 3, 2, 4) (3 rows)
  -> produces 1,219 HTML bytes

Return and teardown
  Middleware unwind (X-Desk-Ms + 4 security headers)
  -> start_response('200 OK') -> server iterates bytes
  -> HttpResponseBase.close -> signal request_finished (drops stale DB sockets)
```

*The whole lifecycle of one synchronous request, with timings from `ch01-bench`. The dashed vertical wall separates what runs inside the view from what runs after the view returns.*

Follow the trace from top to bottom and watch how six subsystems hand the baton across that single call stack.

### From WSGI dictionary to middleware onion

A WSGI server — Gunicorn, uWSGI, or Django's own development server — knows nothing about Django. It calls `WSGIHandler.__call__` with two arguments: a plain Python dictionary (`environ`) holding the HTTP method, path, headers, and input stream, and a `start_response` callback (`django/core/handlers/wsgi.py:WSGIHandler.__call__`).

Before Django even constructs a request object, it records the thread-local script prefix from `"SCRIPT_NAME"` and broadcasts `request_started` (`django/core/signals.py:request_started`). Database connection wrappers listen to `request_started` so they can discard old or broken sockets before any view runs SQL. Only then does `WSGIRequest.__init__` wrap `environ` (`django/core/handlers/wsgi.py:WSGIRequest.__init__`). Even that constructor stays lazy: it extracts the method and path, wraps `"wsgi.input"` in a `LimitedStream` capped at `"CONTENT_LENGTH"`, and leaves query strings, cookies, and POST bodies completely unparsed behind properties until code reads them.

Next, `BaseHandler.get_response` activates the thread-local URLconf and calls `BaseHandler._middleware_chain` (`django/core/handlers/base.py:BaseHandler.get_response`). Although the settings file lists eight middleware strings in a flat list, `BaseHandler.load_middleware` folded them inside-out into a single nested chain of closures when `WSGIHandler` was created (`django/core/handlers/base.py:BaseHandler.load_middleware`). Only our custom timing wrapper is printed in the trace, yet all seven built-in middleware layers wrap the same call — which is why four security headers (`X-Frame-Options`, `X-Content-Type-Options`, `Referrer-Policy`, and `Cross-Origin-Opener-Policy`) show up on line 20 without the view setting a single header.

### Resolution, one eager query, and an unrendered response

At the innermost point of the onion sits `BaseHandler._get_response` (`django/core/handlers/base.py:BaseHandler._get_response`). It calls `URLResolver.resolve` (`django/urls/resolvers.py:URLResolver.resolve`), which strips the leading slash and matches the compiled route pattern, capturing `issue_date="2026-11-25"`. Notice why `URLResolver.resolve` appears twice in the trace: once on the root resolver (`"/editions/2026-11-25/"`) and once on the pattern match beneath it.

`BaseHandler._get_response` invokes the callable returned earlier by `View.as_view` (`django/views/generic/base.py:View.as_view`). That closure allocates a brand-new view instance for this request alone — so per-request attributes stored on the view never bleed between concurrent requests — calls `View.setup`, and enters `View.dispatch`, which routes `"GET"` to `BaseListView.get` (`django/views/generic/list.py:BaseListView.get`).

Inside `get_queryset`, calling `get_object_or_404` forces immediate database evaluation because the view needs the edition row right now (`django/shortcuts.py:get_object_or_404`). That fires SQL #1. Notice the `LIMIT 21` at the end of the SQL: `QuerySet.get` asks for up to `21` rows rather than `2` so that if a query matches duplicates, the `MultipleObjectsReturned` error message can report whether there were `2`, `5`, or *"more than 20"* matching rows without loading an entire table (`django/db/models/query.py:QuerySet.get`).

The queryset returned by `get_queryset`, however, has not touched SQLite. `BaseListView.get` puts that unevaluated `QuerySet` into the context dictionary and calls `render_to_response`, which constructs a `TemplateResponse` and returns it **unrendered** (`django/template/response.py:TemplateResponse`). Touching `SimpleTemplateResponse.content` or iterating the response before rendering raises `ContentNotRenderedError` (`django/template/response.py:SimpleTemplateResponse.content`, `django/template/response.py:ContentNotRenderedError`).

> **Trap.** Because a generic view returns an unrendered `TemplateResponse`, any `with django.db.transaction.atomic():` block or timing context manager placed *inside* the view exits before the template runs the queryset. In our two-hundred-story benchmark above, `99.8%` of the request's work ran outside the view function altogether.

### Deferred rendering wakes up the ORM

Control returns to `BaseHandler._get_response`, which checks whether the response exposes a callable `render` method (`django/core/handlers/base.py:BaseHandler._get_response`). First it runs any `process_template_response` middleware hooks — the entire reason `TemplateResponse` defers rendering is so middleware can still swap the template name or enrich the context before HTML is frozen. Then Django calls `SimpleTemplateResponse.render` (`django/template/response.py:SimpleTemplateResponse.render`).

`SimpleTemplateResponse.render` resolves `"newsroom/edition.html"` and calls `Template.render` (`django/template/base.py:Template.render`). When the template reaches `{% for story in stories %}`, Python calls `iter` on the `QuerySet`, triggering `QuerySet._fetch_all`. Only at that instant does `SQLCompiler` compile and send SQL #2 — a single `INNER JOIN` pulling each story alongside its desk and reporter — followed immediately by SQL #3, which collects the four returned primary keys `(1, 3, 2, 4)` and fetches all matching corrections in one `IN (...)` query, stashing them on each story's prefetch cache. Now when the template checks `"story.corrections.all"` three times per story, all three reads come straight from Python memory with zero extra SQL.

### Unwind, hand-off, and `request_finished`

With `1,219` HTML bytes now sitting in `SimpleTemplateResponse.content`, the response unwinds outward through every middleware layer. The timing wrapper computes elapsed milliseconds and attaches `"X-Desk-Ms"`; `XFrameOptionsMiddleware` and `SecurityMiddleware` stamp the four browser security headers; `WSGIHandler.__call__` calls `start_response("200 OK", response_headers)` and hands the response object back to the WSGI server as an iterable of byte chunks.

Only *after* the WSGI server finishes streaming those bytes to the client does it call `HttpResponseBase.close` (`django/http/response.py:HttpResponseBase.close`). `close` invokes every registered resource closer (such as closing open request upload files) and emits `request_finished`, giving database backends their cue to close expired connections (`django/core/signals.py:request_finished`).

> **Deeper.** Under ASGI, `ASGIHandler.__call__` replaces the synchronous `environ` / `start_response` pair with *scope*, *receive*, and *send* coroutines, streams chunks asynchronously through *send*, and guarantees `request_finished` fires inside a `finally` block once the body completes (`django/core/handlers/asgi.py:ASGIHandler.__call__`). We compare both handlers side by side in [WSGI and ASGI entry points](../handlers/entry-points.md).

That single thirty-line trace raises an immediate architectural question: why did Django choose lazy querysets, unrendered template responses, no cross-query object cache, and a nested synchronous middleware stack in the first place? Those decisions were not accidents — they are five deliberate design bets that explain the rest of the framework.
