Part III · Presentation and systems
Chapter 10: Templates and forms
The promiseA template is HTML with blanks; a form validates fields.
The machineryDjango compiles template source once into a tree of node objects backed by a stacked RenderContext with automatic HTML escaping, while forms run a deterministic three-stage cleaning pipeline.
Part III moves up from the database to the two engines that turn Python objects into HTML and turn HTTP POST bytes back into validated Python state: django/template/ and django/forms/. Both look simple from the outside — templates look like HTML with {{ blanks }} substituted in, and forms look like field dictionaries that return True or False from BaseForm.
Neither description survives reading the source. A Django template is a compiled AST of shared, stateless Node objects built once by Lexer and Parser, cached across requests by Loader, rendered over a stacked Context plus isolated RenderContext, and guarded at every variable write by conditional_escape. Meanwhile, a Django form starts in DeclarativeFieldsMetaclass, deep-copies its fields on every request, runs a strict three-stage BaseForm pipeline where BaseModelForm mutates "form.instance" even when validation fails, and scales to multi-row tables through BaseFormSet and ManagementForm.
Compiling once, caching across requests, and what it saves
ch10-presentation and ch10-bench. Notice that flipping DEBUG=False without the cached loader saves less than 2% (1,261.3 us -> 1,237.0 us ), whereas caching the compiled NodeList tree cuts render time by 3.57x (353.2 us) — and immediately makes thread-safety of every template node class mandatory!Two presentation engines in seven stops
First we trace "desk/"'s "newsroom/ (extending "newsroom/) through the template compiler: lexing and recursive-descent parsing into a NodeList, scoping variables through Context and BlockContext while proving why shared nodes must store per-render state in RenderContext, and measuring the cached template loader alongside render_value_in_context and conditional_escape.
Then we flip directions and submit valid and invalid "POST" payloads into "desk/"'s "StoryForm" and inline "Correction" formsets: metaclass field collection, per-request copy.deepcopy, and BoundField widget rendering; the three-stage full_clean pipeline and ValidationError deletion from "cleaned_data"; ModelFormMetaclass, the _post_clean instance-mutation trap, and "save(commit=False)" + "save_m2m()"; and BaseFormSet + ManagementForm integrity checks powering Admin inlines.
We start with raw template text entering Lexer.tokenize in Lexing, parsing, and the NodeList tree.