Django template escaping

user14412 picture user14412 · Jul 3, 2012 · Viewed 53.2k times · Source

Django templating system provides a few options (filters) for escaping contents in the html, but they are kind of confusing to me as a beginner. Say I'm following a tutorial to make a simple blog, and the blog content needs to be escaped - I trust the content because I am the only one editing it. So the question is should I do it like {{ post.content|autoescape }}, {{ post.content|escape }}, or {{ post.content|safe }} in the html?

Thanks

EDIT: Which filter should I use to have special characters converted to html entities automatically?

EDIT 2: I just realized that autoescape is not a valid filter.

Answer

Paulo Scardine picture Paulo Scardine · Jul 3, 2012

HTML escaping is on by default in Django templates.

Autoescape is a tag. not a filter:

{% autoescape on %}
    {{ post.content }}
{% endautoescape %}

The 'escape' filter escapes a string's HTML. Specifically, it makes these replacements:

  • < is converted to &lt;
  • > is converted to &gt;
  • ' (single quote) is converted to &#39;
  • " (double quote) is converted to &quot;
  • & is converted to &amp;

The 'force_escape' is almost identical to 'escape' except for a few corner cases.

The 'safe' filter will mark your content as safe, so it won't be escaped (will be sent to browser as is).

Which filter should I use to have special characters converted to html entities automatically?

Well, you mean, like converting à to &Atilde;? Stick with utf-8 encoding all the way and forget about those.