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 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 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 binding extra kwargs — it opens "with context (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 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 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/) happens entirely at render time, not compile time — which is why ExtendsNode can even resolve a dynamic parent name from a context variable!
Trace ExtendsNode and BlockNode.render on "edition.html" extending "base.html":
ExtendsNodeindexed every.__init__ BlockNodeinside"edition.html"into"self.blocks"({'title': ..., 'content': ...}).- When
ExtendsNoderuns, it creates a.render BlockContextinsidecontext— a.render_context["block_context"] collectionsmapping each block name to a list of.defaultdict BlockNodeoverrides. BlockContextinserts each template’s blocks at index.add_blocks 0(self), putting the childmost override at the tail (.blocks[name].insert(0, block) [-1]) and the root parent block at index0(blocks['title'] = [base)..title, edition .title] ExtendsNodethen invokes.render "compiled_parentinside._render(context)" "context— keeping the same.render_context .push_state(compiled_parent, isolated_context=False)" RenderContextframe so"block_context"stays visible while rendering"base.html".- When
"base.html"reaches"{% block title %}",BlockNode.rendercalls"block_context— popping.pop('title')" "edition.title"off the tail — clones a freshBlockNodeinstance (type(self)(block) so setting.name, block .nodelist) "blockis thread-safe, renders.context = context" "edition.title", and pushes it back on exit! If"edition.title"evaluates"{{ block,.super }}" BlockNode.supercalls"selfwhile.render(self .context)" "edition.title"is still popped, so the next pop returns"base.title"!
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 (RenderContext), 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), state from Request A silently corrupts Request B (and races under multi-threaded WSGI!). Storing that state in "context 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:
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 follows the exact same rule, caching resolved included templates inside "context 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.