safe Filter

Coding Most Useful


The safe filter indicates that the value is known to be safe and therefore does not need to be escaped. For example, given the following:

blurb = '<p>You are <em>pretty</em> smart!</p>'

This would return unescaped HTML to the client:

{{ blurb|safe }}


<p>You are <em>pretty</em> smart!</p>

The client (e.g., a browser) would then interpret was returned, so your users would see this HTML in the browser:

You are pretty smart!


In most cases, we recommend using this filter instead of the autoescape tag, because it is specific to a variable and less likely to result in unintended (and potentially dangerous) output. However, you must be careful with the safe filter as well.

Consider the following:


blurb_dangerous = '<script>alert("Danger!");</script>'


{{ blurb_dangerous|safe }}



See the commentary on the autoescape tag for more details.

Did we get something wrong? Is there a use case for the safe filter that we should add? Please let us know.

Send Feedback

Official Documentation
This page last updated on Sept. 16, 2020, 7:34 p.m. EST