[Django]-Django template escaping

54👍

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.

29👍

first of all, you should escape your content because you never know (even if you are the one who enter the data) if you are going to need special character (like <, >, ).

The syntax you use show you are uncomfortable with the use of escaping :

this

{% autoescape on %}
    {{ content }}
{% endautoescape %}

is exactly the same as this

{{ content|escape }}

this

{{ content }}

is exactly the same as this <– edit : If the autoescape is OFF (thanks to Paulo Scardine)

{{ content|safe }} 

Safe is use like that :

{% autoescape on %}
    {{ content }}  <-- escape
    {{ content|safe }}  <-- not escape
{% endautoescape %}

12👍

Your question shows you are a little confused about what escaping is.

Escaping is turning non-safe characters – like HTML tags – into escaped versions so that malicious content such as script tags don’t ruin your site. Django does this by default on all content rendered in a template from a variable.

It seems by your comment that you’re the only one editing your content that what you want is to render your variables without the automatic escaping. So, for that, you need to mark it as safe. You can either do this in the template, by either wrapping the whole lot in {% autoescape off %}...{% endautoescape %} tags or via the {{ myvar|safe }} filter on individual variables. Or, you can do it in the view, by calling mark_safe(myvar) on individual variables before passing them to the template.

1👍

To avoid escaping use “safe” (https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#safe):

Marks a string as not requiring further HTML escaping prior to output. When autoescaping is off, this filter has no effect.

To escape use “escape” (https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#escape):

Escapes a string’s HTML.

👤Tadeck

Leave a comment