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

# Context, RenderContext, and inheritance

How does `Context` stack dictionaries for nested scopes, how does `ExtendsNode` resolve overridden `{% block %}` trees, and why must custom tags store per-render state in `RenderContext`?

Rendering a compiled `Template` (`django/template/base.py:Template`) walks its `NodeList` (`django/template/base.py:NodeList`) calling `Node.render_annotated` (`django/template/base.py:Node.render_annotated`) on every node and joining the resulting strings into one `SafeString`. Every node receives one object — a **`Context`** (`django/template/context.py:Context`) — which actually carries **two completely separate dictionary stacks**: `"context.dicts"` for template variables, and **`RenderContext`** (`django/template/context.py:RenderContext`) for internal per-render node state.

## Variable stacks and RequestContext scoping

`Context` subclasses `BaseContext` (`django/template/context.py:BaseContext`), which initializes `"self.dicts"` with a bottom builtins dictionary `{"True": True, "False": False, "None": None}` followed by the caller's dictionary. Looking up `"context[key]"` walks `reversed(self.dicts)` from the top frame down to index `0`.

Whenever a tag introduces a temporary scope — `ForNode.render` (`django/template/defaulttags.py:ForNode.render`) binding `"story"` and `"forloop"`, `BlockNode.render` binding `"block"`, or `IncludeNode.render` (`django/template/loader_tags.py:IncludeNode.render`) binding extra kwargs — it opens `"with context.push(...):"` (`BaseContext.push`). `push` returns a `ContextDict` (`django/template/context.py:ContextDict`) whose `__init__` appends itself onto `"context.dicts"` and whose `__exit__` calls `BaseContext.pop` (`ContextPopException` protects index `0` from ever being popped). That way inner variables shadow outer variables cleanly and vanish automatically when the tag exits.

`RequestContext` (`django/template/context.py:RequestContext`) adds one more layer: it reserves a placeholder slot at `"self._processors_index"` *below* the view's own dictionary via `make_context` (`django/template/context.py:make_context`), then populates that slot by executing every configured context processor (such as `"csrf"` and `"auth"`) inside `RequestContext.bind_template` (`django/template/context.py:RequestContext.bind_template`) and clears it in `"finally:"`. Because the view's dict sits *above* `"_processors_index"`, view-supplied variables always override context processors.

## How `ExtendsNode` and `BlockContext` resolve template inheritance

Template inheritance (`"{% extends 'newsroom/base.html' %}"`) happens entirely at **render time**, not compile time — which is why `ExtendsNode.get_parent` (`django/template/loader_tags.py:ExtendsNode.get_parent`) can even resolve a dynamic parent name from a context variable!

Trace `ExtendsNode.render` (`django/template/loader_tags.py:ExtendsNode.render`) and `BlockNode.render` (`django/template/loader_tags.py:BlockNode.render`) on `"edition.html"` extending `"base.html"`:

1. `ExtendsNode.__init__` indexed every `BlockNode` (`django/template/loader_tags.py:BlockNode`) inside `"edition.html"` into `"self.blocks"` (`{'title': ..., 'content': ...}`).
2. When `ExtendsNode.render` runs, it creates a **`BlockContext`** (`django/template/loader_tags.py:BlockContext`) inside `context.render_context["block_context"]` — a `collections.defaultdict` mapping each block name to a list of `BlockNode` overrides.
3. `BlockContext.add_blocks` inserts each template's blocks at **index `0`** (`self.blocks[name].insert(0, block)`), putting the *childmost* override at the tail (`[-1]`) and the *root* parent block at index `0` (`blocks['title'] = [base.title, edition.title]`).
4. `ExtendsNode.render` then invokes `"compiled_parent._render(context)"` inside `"context.render_context.push_state(compiled_parent, isolated_context=False)"` — keeping the *same* `RenderContext` frame so `"block_context"` stays visible while rendering `"base.html"`.
5. When `"base.html"` reaches `"{% block title %}"`, `BlockNode.render` calls `"block_context.pop('title')"` — popping `"edition.title"` off the tail — clones a fresh `BlockNode` instance (`type(self)(block.name, block.nodelist)`) so setting `"block.context = context"` is thread-safe, renders `"edition.title"`, and pushes it back on exit! If `"edition.title"` evaluates `"{{ block.super }}"`, `BlockNode.super` (`django/template/loader_tags.py:BlockNode.super`) calls `"self.render(self.context)"` while `"edition.title"` is still popped, so the *next* pop returns `"base.title"`!

```text figure=context-and-block-stack
Context.dicts scope stack, BlockContext FIFO queues, and shared-Node isolation (Django 6.1.3)

1. Context.dicts variable stack vs. ExtendsNode BlockContext override queues:
   Context.dicts:  [2] ctx.push(title='Metro Desk') -> [1] {'title': 'Front Page'} -> [0] builtins
                   reversed() lookup: inside='Metro Desk' -> after pop='Front Page'
   BlockContext:   blocks['title']   = [base.title, edition.title]   (pop() renders child first)
                   blocks['content'] = [base.content, edition.content]

2. Why custom Nodes must store per-render state in context.render_context (not self):
   BUG  (self.count += 1):               render 1 -> '1'  | render 2 -> '2'  (LEAKS across requests!)
   SAFE (context.render_context[self]):  render 1 -> '12' | render 2 -> '12' (isolated per render)
```

*Every stack depth, lookup value, and shared-node counter output is verified directly against `ch10-presentation`. Notice why `BlockNode.render` clones itself before storing `"block.context"`: the compiled `BlockNode` inside a cached template is shared across every thread rendering that template!*

## Shared node state and `RenderContext`

Unlike `Context`, which looks upward through every pushed dictionary, `RenderContext` (`django/template/context.py:RenderContext`) overrides `__getitem__`, `__contains__`, and `get` to read **only the top frame `"self.dicts[-1]"`**. Every `Template.render` (`django/template/base.py:Template.render`) call enters `"with context.render_context.push_state(self):"` (`RenderContext.push_state`), pushing a brand-new empty dictionary for that render and popping it on exit.

Why does Django enforce that isolation? Because under the cached template loader (enabled automatically in production when `DEBUG=False`), a single compiled `Template` and all of its `Node` (`django/template/base.py:Node`) instances live in memory for the entire lifetime of the worker process. If a custom template tag stores per-render counters, caches, or cycle iterators on `"self"` (`"self.count += 1"`), state from Request A silently corrupts Request B (and races under multi-threaded WSGI!). Storing that state in `"context.render_context[self]"` keeps each render strictly isolated — even when the same `Node` instance appears twice in one template!

Watch `BaseContext.push` (`django/template/context.py:BaseContext.push`), the shared-`Node` leak vs. `RenderContext` isolation, and `"desk/"`'s `"edition.html"` inheritance render live:

```text recording=ch10-presentation
2. Context stack, BlockContext, and shared-Node vs RenderContext
  Context.dicts depth: initial=2 pushed=3 popped=2 inside='Metro Desk' after='Front Page'
  shared_Node_bug (2 renders): buggy=['1', '2'] render_context_safe=['12', '12']
  edition.html rendered: chars=1213 has_title=True stories_rendered=4
```

Look at `"shared_Node_bug"`: `"buggy"` incremented across two completely separate `Context()` renders (`['1', '2']`), whereas `"render_context_safe"` (with the same `"SafeCounterNode"` rendered twice per template) produced `12` on render 1 and cleanly reset to `12` on render 2! Notice too how Django's built-in `IncludeNode.render` (`django/template/loader_tags.py:IncludeNode.render`) follows the exact same rule, caching resolved included templates inside `"context.render_context.dicts[0].setdefault(self, {})"` so a `"{% include %}"` inside a `"{% for %}"` loop resolves once per render without ever mutating `"self"`.

Now that we know *why* compiled `Node` trees are designed to be reused safely, we measure how much latency the cached template loader actually eliminates — and trace how `VariableNode` protects every interpolated value against XSS — next in [Cached loaders and automatic HTML escaping](loaders-and-escaping.md).
