Django forms templates escape

Streamline Astra :
{% if form.subject.errors %}
    <ol>
    {% for error in form.subject.errors %}
        <li><strong>{{ error|escape }}</strong></li>
    {% endfor %}
    </ol>
{% endif %}

I have taken the above code from a template, a form is passed in under the key 'form' However, i have never encountered |escape before? Is | the or bitwise operator?

Willem Van Onsem :

No, this is the |escape template filter [Django-doc]. As is specified by the documentation:

Escapes a string’s HTML. Specifically, it makes these replacements:

  1. < is converted to &lt;
  2. > is converted to &gt;
  3. ' (single quote) is converted to &#x27;
  4. " (double quote) is converted to &quot;
  5. & is converted to &amp;

Applying escape to a variable that would normally have auto-escaping applied to the result will only result in one round of escaping being done. So it is safe to use this function even in auto-escaping environments. If you want multiple escaping passes to be applied, use the force_escape filter.

It is likely in a {% autoscape off %}…{% endautoescape %} block [Django-doc], since by default Django already escapes the items. It will thus make sure that if the variable is a string that contains characters that can be interpreted as html, these are escaped to prevent that.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=12639&siteId=1
Recommended