---
django: 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a)
part: Presentation and systems
promise: A template is HTML with blanks; a form validates fields.
contents: lexing-and-parsing, context-and-rendering, loaders-and-escaping, form-binding, validation, model-forms, formsets
---

# Templates and forms

Django 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.is_valid` (`django/forms/forms.py:BaseForm.is_valid`).

Neither description survives reading the source. A Django template is a **compiled AST of shared, stateless `Node` objects** (`django/template/base.py:Node`) built once by `Lexer` (`django/template/base.py:Lexer`) and `Parser` (`django/template/base.py:Parser`), cached across requests by `Loader` (`django/template/loaders/cached.py:Loader`), rendered over a stacked `Context` (`django/template/context.py:Context`) plus isolated `RenderContext` (`django/template/context.py:RenderContext`), and guarded at every variable write by `conditional_escape` (`django/utils/html.py:conditional_escape`). Meanwhile, a Django form starts in `DeclarativeFieldsMetaclass` (`django/forms/forms.py:DeclarativeFieldsMetaclass`), deep-copies its fields on every request, runs a strict three-stage `BaseForm.full_clean` (`django/forms/forms.py:BaseForm.full_clean`) pipeline where `BaseModelForm._post_clean` (`django/forms/models.py:BaseModelForm._post_clean`) mutates `"form.instance"` *even when validation fails*, and scales to multi-row tables through `BaseFormSet` (`django/forms/formsets.py:BaseFormSet`) and `ManagementForm` (`django/forms/formsets.py:ManagementForm`).

## Compiling once, caching across requests, and what it saves

```text figure=template-pipeline-and-cache
Template compilation pipeline & cached loader speedup on desk/ edition.html (Django 6.1.3, 7 trials)

1. From edition.html source (904 chars) to escaped HTML (1,213 chars):
   Lexer.tokenize -> 48 tokens (22 TEXT, 9 VAR, 17 BLOCK) via tag_re.split()
   Parser.parse   -> reversed(tokens) O(1), top_nodelist=[ExtendsNode], blocks=['title', 'content']
   cached.Loader  -> get_template_cache[key] (t1 is t2 -> True), skips disk I/O + lexing + parsing
   Render & escape-> RenderContext.push_state, BlockContext FIFO, conditional_escape() on SafeData

2. get_template() + render() of newsroom/edition.html (extends base.html, 4 stories):
   uncached (debug=True)   1261.3 us  (1.00x baseline)
   uncached (debug=False)  1237.0 us  (1.02x faster)
   cached   (debug=True)    365.7 us  (3.45x faster)
   cached   (debug=False)   353.2 us  (3.57x faster)
```

*Every token count and microsecond bar is parsed directly from `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/edition.html"` (extending `"newsroom/base.html"`) through the template compiler: lexing and recursive-descent parsing into a `NodeList` (`django/template/base.py:NodeList`), scoping variables through `Context` and `BlockContext` (`django/template/loader_tags.py:BlockContext`) while proving why shared nodes must store per-render state in `RenderContext`, and measuring the cached template loader alongside `render_value_in_context` (`django/template/base.py: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` (`django/forms/boundfield.py:BoundField`) widget rendering; the three-stage `full_clean` pipeline and `ValidationError` (`django/core/exceptions.py:ValidationError`) deletion from `"cleaned_data"`; `ModelFormMetaclass` (`django/forms/models.py: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` (`django/template/base.py:Lexer.tokenize`) in [Lexing, parsing, and the NodeList tree](presentation/lexing-and-parsing.md).
