The Analogy: A Commercial Mail-Merge Print Shop
A high-volume print shop produces personalized mailers from a single master layout. The layout is a printed sheet with fixed headings, borders, and blank fields; a mail-merge operator drops each customer's name, balance, and offer into the blanks and runs the press. Nobody redesigns the sheet for each customer, and no operator is allowed to invent a new layout mid-run. One master, thousands of filled copies, every one structurally identical. That fixed skeleton with swappable blanks is exactly what a template is: the page shape lives in one file, and only the values change.
Between the customer list and the press sits a copy desk with one standing rule. Anything in a customer's submitted text that looks like a typesetting instruction -- a control code, a font-switch mark, a plate command -- is set as literal ink and printed exactly as the characters appear, never obeyed. A customer who types the characters for "bold on" gets those characters on paper, not bold text. The desk can be overridden, but only for a source the shop genuinely trusts: its own art department sends camera-ready proofs stamped "set as-is," and those pass through untouched. That copy desk is autoescaping, and the "set as-is" stamp is the escape hatch you reach for only when you are certain.
The press room has a second rule that has nothing to do with formatting. It will only mount fresh plates against a work order carrying a numbered chit torn from that morning's job pad -- a chit the shop hands out only for orders raised at its own front counter. A courier who slides a beautifully typed order under the back door without a chit is turned away, because a well-formed order proves nothing about where it came from. The chit, not the typography, proves the order originated inside the shop's own workflow. That chit is the CSRF token, and it is checked on exactly the requests that change something.
The failure is quiet and it begins with fatigue. A marketing partner keeps sending rich copy the desk flags, and rather than stamp each batch trusted, an operator tapes a note over the desk reading "pass everything." The next ordinary customer submission carries a real control code that reprograms the press to overprint every mailer in the run with a stranger's phone number, and ten thousand pieces are in the mail truck before anyone notices. Turning the copy desk off across the board -- or rubber-stamping untrusted text as "set as-is" -- turns one tired shortcut into a shop-wide breach. The narrow, boring default was the only thing standing between one bad line and the entire run.
Syntax or Core Structure
A Django template fills a fixed skeleton with values from a context dictionary, and by default it HTML-escapes every value so user text prints as text and never as live markup. Here is real template syntax, followed by the escaping rule reduced to a plain-Python renderer you can run in any REPL.
{% extends "base.html" %}
{% block content %}
<h1>{{ product.name }}</h1>
<p>{{ comment }}</p>
<div>{{ bio|safe }}</div>
{% endblock %}
The {{ ... }} slots are value substitutions; {% ... %} tags are control flow. The |safe filter on bio says "do not escape this, I promise it is trusted HTML." Everything else is escaped. This renderer models that exact behaviour: substitute each slot, escape by default, and honour |safe as the single opt-out.
def esc(s):
s = s.replace("&", "&")
s = s.replace("<", "<").replace(">", ">")
s = s.replace('"', """).replace("'", "'")
return s
def render(template, context):
out = []
i = 0
while i < len(template):
start = template.find("{{", i)
if start == -1:
out.append(template[i:])
break
out.append(template[i:start])
end = template.find("}}", start)
key = template[start + 2:end].strip()
raw = key.endswith("|safe")
name = key[:-5].strip() if raw else key
out.append(context[name] if raw else esc(context[name]))
i = end + 2
return "".join(out)
context = {"name": "Ada & Co", "comment": "<b>hi</b>", "bio": "<i>trusted</i>"}
template = """name: {{ name }}
comment: {{ comment }}
bio: {{ bio|safe }}"""
print(render(template, context))
Output:
name: Ada & Co
comment: <b>hi</b>
bio: <i>trusted</i>
The ampersand and the angle brackets came through as HTML entities, so a browser renders them as the literal characters the user typed. Only bio, marked |safe, kept its raw tags -- which is fine here because the value is ours, and a disaster the moment it is something a stranger can set.
Technical Depth: Escaping, CSRF and the Admin's Query Budget
Every value is escaped unless you mark it safe
Autoescaping rewrites five characters before they reach the browser. Learn the map and the reason for each, because these five are exactly what an attacker needs to break out of text and into live markup.
| Raw character | Django prints | Attack it blocks |
|---|---|---|
| ampersand | & | breaks out of an existing entity |
| less-than | < | opens a script or img tag |
| greater-than | > | closes an injected tag |
| double quote | " | ends an attribute and injects another |
| single quote | ' | ends a single-quoted attribute |
The ampersand is escaped first on purpose: if you replaced < before &, you would double-escape the & in <. The |safe filter and {% autoescape off %} both switch this off, and both are correct only for HTML you generated or sanitised yourself. Marking user input safe is the single most common way a Django site ships stored XSS.
The CSRF token gates unsafe methods
Cross-site request forgery works by making a victim's browser send a state-changing request to your site, carrying their session cookie automatically. Django's defence is a per-session token that must accompany every unsafe request. The token is checked on the methods that change state and skipped on the ones that only read.
| HTTP method | Token checked | Reason |
|---|---|---|
| GET | no | safe, must be side-effect free |
| HEAD | no | safe, headers only |
| OPTIONS | no | safe, capability probe |
| POST | yes | creates or submits state |
| PUT | yes | replaces a resource |
| PATCH | yes | edits a resource |
| DELETE | yes | removes a resource |
The rule is not "check tokens on forms," it is "check tokens on unsafe methods." That is why a GET that changes state is a real bug: it slips past CSRF protection entirely because the framework trusts GET to be read-only. This stand-in encodes the exact decision the middleware makes.
SAFE = {"GET", "HEAD", "OPTIONS"}
def csrf_check(method, token, session_token):
if method in SAFE:
return "200 ok (safe method)"
if token is None:
return "403 forbidden (token missing)"
if token != session_token:
return "403 forbidden (token mismatch)"
return "200 ok (token valid)"
session_token = "s3cr3t"
requests = [
("GET", None, "s3cr3t"),
("POST", "s3cr3t", "s3cr3t"),
("POST", "wrong", "s3cr3t"),
("POST", None, "s3cr3t"),
("DELETE", "s3cr3t", "s3cr3t"),
]
for method, token, sess in requests:
print("%-6s -> %s" % (method, csrf_check(method, token, sess)))
Output:
GET -> 200 ok (safe method)
POST -> 200 ok (token valid)
POST -> 403 forbidden (token mismatch)
POST -> 403 forbidden (token missing)
DELETE -> 200 ok (token valid)
The safe GET sailed through with no token; the valid POST and DELETE passed on a matching token; the mismatched and missing tokens were both rejected with 403. That 403 is the framework doing its job, not a bug to route around with @csrf_exempt.
The admin is not exempt from N+1
The admin's changelist renders one row per object, and any column that reads a foreign key -- category on a product, author on a comment -- costs one extra query per row unless you tell the admin to join. Set list_select_related and the framework issues a single joined query for the whole page; omit it and a 200-row changelist quietly fires 201 queries. The next section shows that arithmetic on a small feed.
Real World Example: A Moderated Comment Feed
A comment feed shows the three ideas at once. Every comment is rendered through the escaping template, so ordinary user text is neutralised; a small number of comments are flagged trusted (an editor's note) and rendered raw with the |safe escape hatch; and the moderation admin lists them all with the author foreign key, which is where the N+1 budget bites. Here is the whole thing reduced to a plain-Python REPL that prints the numbers exactly.
def esc(s):
s = s.replace("&", "&")
s = s.replace("<", "<").replace(">", ">")
s = s.replace('"', """).replace("'", "'")
return s
COMMENTS = [
{"author": "Ada", "body": "great product", "trusted": True},
{"author": "Bob", "body": "<script>steal()</script>", "trusted": False},
{"author": "Cara", "body": "<b>bold</b> and nice", "trusted": False},
{"author": "Dan", "body": "<i>editor note</i>", "trusted": True},
{"author": "Eve", "body": "5 < 10 always", "trusted": False},
]
def render_body(c):
return c["body"] if c["trusted"] else esc(c["body"])
autoescaped = sum(1 for c in COMMENTS if not c["trusted"])
raw_kept = sum(1 for c in COMMENTS if c["trusted"])
neutralized = sum(1 for c in COMMENTS if not c["trusted"] and "<script" in c["body"])
sample = ""
for c in COMMENTS:
if not c["trusted"] and "<script" in c["body"]:
sample = render_body(c)
break
naive_queries = 1 + len(COMMENTS)
select_related_queries = 1
print("rendered: %d" % len(COMMENTS))
print("autoescaped: %d" % autoescaped)
print("raw kept (trusted): %d" % raw_kept)
print("neutralized scripts: %d" % neutralized)
print("sample escaped: %s" % sample)
print("naive admin queries: %d" % naive_queries)
print("select_related queries: %d" % select_related_queries)
Output:
rendered: 5
autoescaped: 3
raw kept (trusted): 2
neutralized scripts: 1
sample escaped: <script>steal()</script>
naive admin queries: 6
select_related queries: 1
Five comments were rendered. Three were untrusted and so passed through the escaper; two were flagged trusted and rendered raw through the |safe path. That split is the entire security posture of the feed on one line: the default is escape, and the exceptions are counted and few.
The one comment containing a <script tag was Bob's, and because it was untrusted it came out as <script>steal()</script> -- inert text a browser prints rather than runs. Had that same body been flagged trusted, the tag would have shipped live. The escaper is what stands between a hostile comment and every other reader's browser.
The query budget tells the operational half of the story. Listing five comments with their author in the admin costs a naive six queries (one for the list, one per row for the author), and list_select_related("author") collapses that to one joined query. At five rows nobody notices; at a five-hundred-row moderation queue the naive version fires five hundred and one queries and the page visibly stalls.
The code has real flaws worth naming. The neutralized counter only greps for the literal substring <script, so it silently misses <img onerror=...>, <svg onload=...>, inline event handlers, and javascript: URLs -- it undercounts the very thing it claims to measure. The trusted flag is a bare per-row boolean with no record of who set it or when, so one mislabelled row ships live HTML with no audit trail. render_body applies zero sanitisation on the trusted path, meaning a single compromised editor account is instant stored XSS with no second line of defence. And the query figure models exactly one lookup per row, ignoring the admin's own count and pagination queries, so 1 is the floor, not the true total.
Common Mistakes
- Marking user input
|safe. The moment a value a stranger can influence -- a comment, a bio, a product review -- is rendered with|safeor inside{% autoescape off %}, you have a stored XSS hole. Sanitise server-side with an allowlist first, then mark the sanitised result safe; never the raw input.
- Deleting
{% csrf_token %}to silence a 403. The 403 is the protection working. Removing the token does not fix the form, it disables the defence. If afetchcall gets the 403, send theX-CSRFTokenheader instead.
- Scattering
@csrf_exempton state-changing views. Exempting a view that writes data removes CSRF protection from exactly the endpoint that needs it. For webhooks, verify the provider's signature; for AJAX, send the header.
- Treating
GETas a place to change state. AGETthat deletes or mutates bypasses CSRF entirely, because the framework trusts safe methods to be read-only. Anything that changes state must bePOST,PUT,PATCH, orDELETE.
- Two apps shipping the same bare template name.
product_list.htmlin two apps shadow each other, and the loader returns the first match across all apps. Namespace every template asapp/templates/app/name.htmlso the path is unambiguous.
- Forgetting
list_select_relatedon an admin changelist. A changelist that displays a foreign key runs one query per row without it. On a large table the admin page becomes the slowest page in the app, and nobody profiles the admin.
- Doing real computation in templates. The template language is deliberately limited so logic stays in views and models where it is testable. If a template needs a calculation, move it to an annotated QuerySet or a model property.
- Building customer-facing pages in the admin. The admin exposes your schema for trusted staff, not your workflows for customers. Every hour spent bending it into a public surface is an hour that would have built the real page.
- Assuming the admin enforces row-level rules. Admin permissions are per-model and per-action. "Only your own region" requires a
get_querysetoverride on every relevant admin class, and one omission leaks every row.
Best Practices
- Let autoescaping do its job. Treat the default as sacred and reach for
|safeonly on HTML you generated or sanitised yourself. When you must accept rich text, run it through an allowlist sanitiser server-side.
- Namespace templates by app. Store them as
catalog/templates/catalog/product_list.htmlso the loader can never return another app's file by accident.
- Keep logic out of templates. Templates present; views and models decide. Push computation into annotated QuerySets and model properties where tests can reach it.
- Always include
{% csrf_token %}in POST forms. For JavaScript requests, read thecsrftokencookie and send it as theX-CSRFTokenheader rather than exempting the view.
- Prefer
{% extends %}for skeletons and{% include %}for fragments. One base layout with named blocks beats copying markup into every template.
- Set
list_select_relatedandreadonly_fieldson every admin class. Join foreign keys shown in the changelist, and make audit timestamps non-editable.
- Put the admin on a non-default URL behind strong staff auth. Keep
is_superuserrare, never share admin accounts, and remember that admin deletes honouron_deletecascades.
- Verify webhook signatures instead of exempting CSRF blindly. A token-in-header API is not cookie-exposed, but scope any exemption to that single view and confirm the request's origin another way.
Practice Exercises
- Trace the escaper by hand. Take the context
{"title": "Tom & Jerry", "note": "<i>ok</i>"}and the template{{ title }} / {{ note }}, then predict the rendered line character for character before runningrender. Confirm the ampersand becomes&and the italics tag becomes<i>ok</i>.
- Extend
csrf_checkwith an origin test. Add a fourth parameteroriginand reject any unsafe request whose origin is not your own host with"403 forbidden (bad origin)", checked before the token. Re-run the request batch with one spoofed origin and confirm only that row changes.
- Write a real allowlist sanitiser. Replace the
trustedshortcut with asanitisefunction that keeps only<b>and<i>and escapes everything else, then render every comment through it. Show that Bob's<script>is still neutralised while Cara's<b>bold</b>survives.
- Fix the admin N+1. Model a
ProductAdminchangelist over 200 rows that displayscategory, count the naive query total, then addlist_select_related("category")and count again. State the two numbers and explain why the join wins even though it fetches more columns per row.