Django 6.1.3

10.2 Templates and forms

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 walks its NodeList calling Node.render_annotated on every node and joining the resulting strings into one SafeString. Every node receives one object — a Context — which actually carries two completely separate dictionary stacks: "context.dicts" for template variables, and RenderContext for internal per-render node state.

Variable stacks and RequestContext scoping

Context subclasses 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 binding "story" and "forloop", BlockNode.render binding "block", or IncludeNode.render binding extra kwargs — it opens "with context.push(...):" (BaseContext.push). push returns a 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 adds one more layer: it reserves a placeholder slot at "self._processors_index" below the view’s own dictionary via make_context, then populates that slot by executing every configured context processor (such as "csrf" and "auth") inside 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 can even resolve a dynamic parent name from a context variable!

Trace ExtendsNode.render and BlockNode.render on "edition.html" extending "base.html":

  1. ExtendsNode.__init__ indexed every BlockNode inside "edition.html" into "self.blocks" ({'title': ..., 'content': ...}).
  2. When ExtendsNode.render runs, it creates a 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 calls "self.render(self.context)" while "edition.title" is still popped, so the next pop returns "base.title"!
Figure 10.2 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 overrides __getitem__, __contains__, and get to read only the top frame "self.dicts[-1]". Every 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 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, the shared-Node leak vs. RenderContext isolation, and "desk/"'s "edition.html" inheritance render live:

Recorded on Django 6.1.3 ch10-presentation script
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 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.