---
django: 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a)
part: Presentation and systems
promise: "A template is HTML with blanks; a form validates fields."
---

# 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 that binds raw strings to typed Python values.

When `Template` receives a string of markup, `Lexer` slices it into text, variable, tag, and comment tokens and `Parser` folds those tokens into a `NodeList` of `Node` objects (`django/template/base.py:Template`, `django/template/base.py:Lexer`, `django/template/base.py:Parser`, `django/template/base.py:Node`). Rendering walks that node tree against a `Context`, pushing and popping dictionaries so block scopes never leak across sibling nodes (`django/template/base.py:Template.render`).

## Compiled once, rendered many times

The default cached template loader keeps compiled `Template` objects in memory for the life of the worker process (`django/template/base.py:Template`, `django/template/loaders/cached.py:Loader`). Every request skips lexing and parsing entirely and walks the existing node tree, paying only variable resolution and escaping per render.

> **Trap.** Because a compiled `Node` instance is shared across every request in a worker process (`django/template/base.py:Node`), storing per-request state on a node corrupts concurrent responses. Request-local state belongs in `RenderContext`, never on the node.
