1👍
You can use format_html()
for it. The django.utils.html
module provides some low level utilities for escaping HTML.
This function is to be preferred over string interpolation using %
or str.format
directly, because it applies escaping to all arguments – just like the Template system applies escaping by default.
You could have used mark_safe()
to escape HTML like below:
mark_safe(u"%s <b>%s</b> %s" % (some_html,
escape(some_text),
escape(some_other_text),
))
But by using the below code,
format_html(u"{0} <b>{1}</b> {2}", mark_safe(some_html), some_text, some_other_text)
you don’t need to apply escape() to each argument and risk a bug and an XSS vulnerability if you forget one.
You can use the autoescape
built-in template tag in your template.
This tag takes either on
or off
as an argument and that determines whether auto-escaping is in effect inside the block. The block is closed with an endautoescape
ending tag.
When auto-escaping is in effect, all variable content has HTML escaping applied to it before placing the result into the output (but after any filters have been applied). This is equivalent to manually applying the escape filter to each variable.
{% autoescape on %}
{{ image_object }}
{% endautoescape %}
This should solve your problem.