Escaping in Django Templates
Escaping keeps reader-typed text safe in a page. Django turns < and > into harmless codes by default.
Make the views
Two views share one value. Each one renders it a different way.
def safe_page(request):
return render(request, "safe.html", {"text": "<b>bold</b>"})
def raw_page(request):
return render(request, "raw.html", {"text": "<b>bold</b>"})Escaped by default
The template prints the value as plain text. The <b> tags become harmless codes.
<p>{{ text }}</p>Raw with |safe
The |safe filter switches escaping off. The same value now comes out as bold HTML.
<p>{{ text|safe }}</p>Ask for both pages
The test client visits each address. The prints place the escaped page next to the raw page.
from django.test import Client
client = Client()
print(client.get("/safe/").content.decode())
print(client.get("/raw/").content.decode())Example
import django
from django.conf import settings
settings.configure(
DEBUG=True,
SECRET_KEY="key",
ROOT_URLCONF=__name__,
ALLOWED_HOSTS=["*"],
TEMPLATES=[{"BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "APP_DIRS": True}],
)
django.setup()
from django.template import Context, Template
template = Template("<p>{{ text }}</p>")
print(template.render(Context({"text": "<b>bold</b>"})))
template = Template("<p>{{ text|safe }}</p>")
print(template.render(Context({"text": "<b>bold</b>"})))
Key points
- {{ text }} escapes < and > in the value.
- Escaped text stays plain text, never HTML.
- The |safe filter switches escaping off for one value.
- Use |safe only for HTML written by the app itself.
In this example, the setup lines configure Django. The program renders the same value two ways with Template and Context. A real project keeps templates in files. The first template escapes the value, so the tags stay plain text on the page. The second template uses |safe, so bold HTML comes out.
Note
Never mark reader-typed text as safe.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What comes out of {{ text }} for the value "<b>bold</b>"?