Escape HTML at Render Time, Not When Storing User Input
Django templates escape every variable by default, so the safe way to show user text is to store it raw and let the template encode it on output. Calling escape() on input and rendering with |safe swaps that guarantee for a convention: the page stays safe only while every code path that writes the field remembers to escape first.
The Pattern That Looks Safe
# views.py
from django.utils.html import escape
def add_category(request):
category_name = escape(request.POST.get("category-name"))
Category.objects.create(name=category_name, slug=string_to_slug(category_name))
return redirect("tasks_index_path")
{% for category in categories %}
<li>{{ category.name|safe }}</li>
{% endfor %}
It renders correctly as long as this view is the only writer of Category.name.
Stored Entities Leak Everywhere Else
Escaping before storage puts HTML entities into data that isn't HTML:
Tom & Jerryis stored asTom & Jerry, so a slug built from it (withslugify(), for example) becomestom-amp-jerry, and CSV exports, JSON APIs, emails and the admin all show&.- Rendered anywhere without
|safe, the value is escaped a second time and the page shows&literally.
Where Encoding Belongs
HTML escaping is also the wrong encoding outside HTML text: to hand a value to JavaScript, use the json_script filter rather than escape().
References
- Web Application and Django Security MOC - hub for output encoding and XSS notes.
- Rendering Untrusted Markdown with mark_safe Causes XSS - the same failure through
mark_safe(): marking text safe switches auto-escaping off. - Sanitizing Markdown Output with an HTML Allowlist - what to do when some HTML has to survive.
- Django documentation: Automatic HTML escaping - default auto-escaping and the
safefilter. - Django documentation: format_html() - building HTML fragments with escaped arguments.
- OWASP Cross Site Scripting Prevention Cheat Sheet - output encoding per context.
Review cards
Flashcard Why store user text raw and escape it at render time?
Auto-escaping then protects the output whichever code path wrote the value, and the stored data stays plain text that slugs, CSV exports, JSON and emails can use.
Flashcard Why does escaping a field at input and rendering it with |safe lead to stored XSS?
Other writers (the admin, the shell, a migration, an API) save the field without escaping, and |safe renders what they wrote as live HTML.
Quiz Which approach protects a Django page from XSS in user-entered text?
- Escape on input, render with |safe
- Store the text raw, render it without |safe
- Store it raw, render it with |safe
- escape() on input, mark_safe() on output
Templates escape every variable by default. |safe and mark_safe() switch that off, so the page is then only as safe as every writer of the field.