#!/usr/bin/env python3 """Deterministic Django 6.1.3 trace for Chapter 10 (Templates and forms). Inspects template lexing/parsing over desk's edition.html, Context/RenderContext/ BlockContext and the shared-Node state bug, cached loader behavior and conditional_escape, DeclarativeFieldsMetaclass and BoundField on StoryForm, the three-stage full_clean pipeline, ModelForm._post_clean instance mutation on invalid forms + save(commit=False)/save_m2m, and BaseFormSet/ManagementForm/ BaseInlineFormSet on Story + Correction. """ from __future__ import annotations import sys from collections import Counter from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) from harness import Recorder, boot_desk def main() -> None: seeded = boot_desk() from django import forms from django.forms import inlineformset_factory from django.template import Context, Engine, Node, Template from django.template.base import Lexer, Parser, TokenType from django.template.loader import get_template from django.template.loader_tags import BlockNode, ExtendsNode from django.template.defaulttags import ForNode, IfNode from django.utils.html import conditional_escape from django.utils.safestring import mark_safe from newsroom.forms import StoryForm from newsroom.models import Correction, Desk, Edition, Reporter, Story rec = Recorder("ch10-presentation") # 1. Lexing and parsing desk/newsroom/templates/newsroom/edition.html with rec.block("1. Lexer.tokenize and Parser.parse over desk edition.html"): tpl_wrapper = get_template("newsroom/edition.html") tpl = tpl_wrapper.template tokens = Lexer(tpl.source).tokenize() type_counts = Counter(t.token_type.name for t in tokens) rec.emit( f"edition.html: chars={len(tpl.source)} tokens={len(tokens)} " f"counts=TEXT:{type_counts['TEXT']},VAR:{type_counts['VAR']},BLOCK:{type_counts['BLOCK']}" ) rec.emit("first_8_tokens:") for tok in tokens[:8]: preview = tok.contents.replace("\n", "\\n") rec.emit(f" L{tok.lineno:02d} {tok.token_type.name:<5} {preview!r}") top_nodes = [type(n).__name__ for n in tpl.nodelist] extends_node = tpl.nodelist.get_nodes_by_type(ExtendsNode)[0] block_names = [b.name for b in tpl.nodelist.get_nodes_by_type(BlockNode)] for_nodes = tpl.nodelist.get_nodes_by_type(ForNode) if_nodes = tpl.nodelist.get_nodes_by_type(IfNode) rec.emit(f"top_nodelist = {top_nodes}") rec.emit( f"extends_parent={extends_node.parent_name.token!r} blocks={block_names} " f"if_nodes={len(if_nodes)} for_nodes={len(for_nodes)} " f"for_loop_children={len(for_nodes[0].nodelist_loop)} " f"for_empty_children={len(for_nodes[0].nodelist_empty)}" ) # 2. Context stack, BlockContext inheritance, and the shared-Node state bug with rec.block("2. Context stack, BlockContext, and shared-Node vs RenderContext"): ctx = Context({"title": "Front Page"}) depth_initial = len(ctx.dicts) with ctx.push(title="Metro Desk", section="MTR"): inside_title = ctx["title"] depth_pushed = len(ctx.dicts) after_title = ctx["title"] depth_popped = len(ctx.dicts) rec.emit( f"Context.dicts depth: initial={depth_initial} pushed={depth_pushed} " f"popped={depth_popped} inside={inside_title!r} after={after_title!r}" ) # Demonstrate shared-Node mutation bug vs RenderContext isolation class BuggyCounterNode(Node): def __init__(self): self.count = 0 def render(self, context): self.count += 1 return str(self.count) class SafeCounterNode(Node): def render(self, context): n = context.render_context.get(self, 0) + 1 context.render_context[self] = n return str(n) t_buggy = Template("") t_buggy.nodelist = [BuggyCounterNode()] t_buggy_out = [ "".join(n.render(c) for n in t_buggy.nodelist) for c in (Context(), Context()) ] # Proper Template.render() pushes isolated RenderContext frame per render t_safe = Template("") safe_node = SafeCounterNode() t_safe.nodelist.append(safe_node) t_safe.nodelist.append(safe_node) t_safe_r1 = t_safe.render(Context()) t_safe_r2 = t_safe.render(Context()) rec.emit( f"shared_Node_bug (2 renders): buggy={t_buggy_out} " f"render_context_safe={[t_safe_r1, t_safe_r2]}" ) edition = Edition.objects.get(slug="2026-11-25") stories = list( Story.objects.filter(edition=edition, status=Story.Status.PUBLISHED) .select_related("desk", "reporter") .prefetch_related("corrections") ) rendered = tpl.render(Context({"edition": edition, "stories": stories})) rec.emit( f"edition.html rendered: chars={len(rendered)} " f"has_title={'Wednesday Final — 2026-11-25' in rendered} " f"stories_rendered={rendered.count('
  • ')}" ) # 3. Cached template loader & automatic HTML escaping (conditional_escape) with rec.block("3. Cached template loader and conditional_escape"): templates_dir = str(Path(__file__).resolve().parent.parent / "desk" / "newsroom" / "templates") cached_engine = Engine( dirs=[templates_dir], loaders=[ ( "django.template.loaders.cached.Loader", ["django.template.loaders.filesystem.Loader"], ) ], ) t1 = cached_engine.get_template("newsroom/edition.html") t2 = cached_engine.get_template("newsroom/edition.html") cache_keys = sorted(cached_engine.template_loaders[0].get_template_cache.keys()) rec.emit(f"cached_loader: t1_is_t2={t1 is t2} cache_keys={cache_keys}") raw_xss = '' safe_html = mark_safe("Breaking") t_esc = Template("{{ val }}") t_off = Template("{% autoescape off %}{{ val }}{% endautoescape %}") rec.emit(f"autoescape_plain = {t_esc.render(Context({'val': raw_xss}))!r}") rec.emit(f"autoescape_safe = {t_esc.render(Context({'val': safe_html}))!r}") rec.emit(f"autoescape_off = {t_off.render(Context({'val': raw_xss}))!r}") rec.emit( f"conditional_escape(plain)={conditional_escape(raw_xss)!r} " f"conditional_escape(safe)={conditional_escape(safe_html)!r}" ) # 4. DeclarativeFieldsMetaclass, deep-copied fields, and BoundField on StoryForm with rec.block("4. Form metaclass, field deep-copying, and BoundField on StoryForm"): f1 = StoryForm(prefix="draft") f2 = StoryForm() rec.emit( f"StoryForm.base_fields = {list(StoryForm.base_fields.keys())}" ) rec.emit( f"per_instance_deepcopy: f1_is_base={f1.fields is StoryForm.base_fields} " f"field_obj_shared={f1.fields['headline'] is f2.fields['headline']}" ) bf = f1["headline"] rec.emit( f"BoundField('headline', prefix='draft'): html_name={bf.html_name!r} " f"auto_id={bf.auto_id!r} widget={type(bf.field.widget).__name__} " f"cached={f1['headline'] is bf}" ) rec.emit(f"widget_html = {bf.as_widget()!r}") # 5. Three-stage full_clean pipeline on StoryForm (field error + cross-field error) with rec.block("5. Three-stage full_clean pipeline on StoryForm"): metro = Desk.objects.get(slug="metro") cora = Reporter.objects.get(name="Cora") # City Hall reporter! ed = Edition.objects.get(slug="2026-11-25") bad_post = { "headline": "ALL CAPS ALERT", "slug": "all-caps-alert", "desk": str(metro.pk), "reporter": str(cora.pk), "edition": str(ed.pk), "priority": "1", "body": "Lead paragraph.", } form_bad = StoryForm(data=bad_post) valid_bad = form_bad.is_valid() rec.emit( f"invalid_submit: is_valid={valid_bad} " f"headline_in_cleaned_data={'headline' in form_bad.cleaned_data} " f"cleaned_keys={sorted(form_bad.cleaned_data.keys())}" ) rec.emit(f"error_dict = {dict(form_bad.errors.get_json_data())!r}") good_post = { **bad_post, "headline": "Council approves ferry dock", "slug": "council-approves-ferry-dock", "reporter": str(Reporter.objects.get(name="Ada").pk), } form_ok = StoryForm(data=good_post) rec.emit( f"valid_submit: is_valid={form_ok.is_valid()} " f"errors={dict(form_ok.errors)} " f"cleaned_headline={form_ok.cleaned_data['headline']!r}" ) # 6. ModelForm._post_clean mutating instance on invalid form + save(commit=False) with rec.block("6. ModelForm._post_clean instance mutation trap and save(commit=False)"): s1 = Story.objects.get(slug="bridge-bond-passes") orig_headline = s1.headline dup_post = { "headline": "Mutated Headline In Memory", "slug": "water-main-repair", # duplicates s2 -> fails validate_unique! "desk": str(s1.desk_id), "reporter": str(s1.reporter_id), "edition": str(s1.edition_id), "priority": "1", "body": s1.body, } form_dup = StoryForm(data=dup_post, instance=s1) is_valid_dup = form_dup.is_valid() rec.emit( f"unique_fail: is_valid={is_valid_dup} " f"errors={list(form_dup.errors.keys())}" ) rec.emit( f"instance_mutated_despite_invalid: before={orig_headline!r} " f"after_is_valid={s1.headline!r} db_still={Story.objects.get(pk=s1.pk).headline!r}" ) # Restore in-memory s1, demonstrate save(commit=False) attaching save_m2m dynamically form_new = StoryForm(data=good_post) assert form_new.is_valid() has_save_m2m_before = hasattr(form_new, "save_m2m") unsaved = form_new.save(commit=False) has_save_m2m_after = hasattr(form_new, "save_m2m") rec.emit( f"save(commit=False): pk={unsaved.pk!r} adding={unsaved._state.adding} " f"has_save_m2m_before={has_save_m2m_before} has_save_m2m_after={has_save_m2m_after}" ) # 7. BaseFormSet, ManagementForm tampering, and BaseInlineFormSet on Story/Correction with rec.block("7. BaseFormSet, ManagementForm tampering, and BaseInlineFormSet"): CorrectionFormSet = inlineformset_factory( Story, Correction, fields=["note", "issued_at"], extra=1, can_delete=True, ) s1_fresh = Story.objects.get(slug="bridge-bond-passes") fs_unbound = CorrectionFormSet(instance=s1_fresh) rec.emit( f"inline_unbound: prefix={fs_unbound.prefix!r} " f"initial={fs_unbound.initial_form_count()} total={fs_unbound.total_form_count()} " f"max_num={fs_unbound.max_num} absolute_max={fs_unbound.absolute_max}" ) rec.emit( f"form_prefixes = {[f.prefix for f in fs_unbound.forms]} " f"extra_empty_permitted={fs_unbound.forms[-1].empty_permitted}" ) # Missing ManagementForm POST aborts validation immediately fs_missing = CorrectionFormSet( data={"corrections-0-note": "Tampered"}, instance=s1_fresh, ) rec.emit( f"missing_mgmt: is_valid={fs_missing.is_valid()} " f"total_forms={fs_missing.total_form_count()} " f"non_form_errors={list(fs_missing.non_form_errors())}" ) # Valid bound inline formset editing existing #0 and leaving extra #2 blank c_list = list(s1_fresh.corrections.order_by("id")) valid_fs_data = { "corrections-TOTAL_FORMS": "3", "corrections-INITIAL_FORMS": "2", "corrections-MIN_NUM_FORMS": "0", "corrections-MAX_NUM_FORMS": "1000", "corrections-0-id": str(c_list[0].pk), "corrections-0-story": str(s1_fresh.pk), "corrections-0-note": "Updated roll call note.", "corrections-0-issued_at": "2026-11-25 11:20:00", "corrections-1-id": str(c_list[1].pk), "corrections-1-story": str(s1_fresh.pk), "corrections-1-note": c_list[1].note, "corrections-1-issued_at": "2026-11-25 12:05:00", "corrections-2-id": "", "corrections-2-story": str(s1_fresh.pk), "corrections-2-note": "", "corrections-2-issued_at": "", } fs_bound = CorrectionFormSet(data=valid_fs_data, instance=s1_fresh) rec.emit( f"valid_inline_post: is_valid={fs_bound.is_valid()} " f"changed_forms={[f.prefix for f in fs_bound.forms if f.has_changed()]} " f"extra_form_cleaned_empty={fs_bound.forms[2].cleaned_data == {}}" ) rec.write() if __name__ == "__main__": main()