Escape HTML at Render Time, Not When Storing User Input

In progress Django AppSec

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 & Jerry is stored as Tom &amp; Jerry, so a slug built from it (with slugify(), for example) becomes tom-amp-jerry, and CSV exports, JSON APIs, emails and the admin all show &amp;.
  • Rendered anywhere without |safe, the value is escaped a second time and the page shows &amp; 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

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.