How to Use Autoescape in Django Templates: Simple Guide
In Django templates, use the
{% autoescape %} tag to enable or disable automatic HTML escaping of variables. Wrap the content inside {% autoescape on %} or {% autoescape off %} blocks to control escaping behavior explicitly.Syntax
The {% autoescape %} tag controls whether Django automatically escapes HTML special characters in template variables. It has two main forms:
{% autoescape on %} ... {% endautoescape %}: Enables autoescaping inside the block.{% autoescape off %} ... {% endautoescape %}: Disables autoescaping inside the block.
By default, Django templates have autoescaping enabled.
django
{% autoescape on %}
{{ variable }}
{% endautoescape %}
{% autoescape off %}
{{ variable }}
{% endautoescape %}Example
This example shows how to disable autoescaping for a variable that contains HTML code, so it renders as HTML instead of escaped text.
django
{% autoescape off %}
{{ html_content }}
{% endautoescape %}
<p>Normal autoescaping:</p>
{{ html_content }}Output
<b>Bold Text</b>
<b>Bold Text</b>
Common Pitfalls
Common mistakes include:
- Disabling autoescape without sanitizing input, which can cause security risks like XSS attacks.
- Forgetting to close the
{% endautoescape %}tag, causing template errors. - Assuming autoescape is off by default; it is on by default in Django templates.
django
{# Wrong: forgetting endautoescape #}
{% autoescape off %}
{{ user_input }}
{# Right: always close the block #}
{% autoescape off %}
{{ user_input }}
{% endautoescape %}Quick Reference
| Tag | Description |
|---|---|
| {% autoescape on %} ... {% endautoescape %} | Enable autoescaping inside the block |
| {% autoescape off %} ... {% endautoescape %} | Disable autoescaping inside the block |
| {{ variable }} | Escapes HTML by default unless inside autoescape off |
| {{ variable|safe }} | Marks variable as safe to skip escaping |
Key Takeaways
Use {% autoescape on %} and {% autoescape off %} to control HTML escaping in Django templates.
Autoescaping is enabled by default to protect against XSS attacks.
Disable autoescaping only when you trust the content and want to render raw HTML.
Always close autoescape blocks with {% endautoescape %} to avoid template errors.
Use the safe filter as an alternative to disable escaping for specific variables.