[Answered ]-Django | Auto Escape On / Off | Single Quotes | JSON

2👍

The autoescape tag escapes special HTML characters (< and >), not single quotes.

If you want to escape single quotes, you can write a custom template filter.

For example:

from django import template


register = template.Library()


@register.filter
def escape_single_quotes(string):
    # The two backslashes are interpreted as a single one
    # because the backslash is the escaping character.
    return string.replace("'", "\\'")

If you do not wish to use a template filter, what you can do is this:

{# Note the type is not "text/javascript" so the browser does not try to interpret the content. #}
<script id="jresp" type="application/json">{{ jresp }}</script>
<script>
  var jsresp = document.getElementById('jsreps').innerHTML;
</script>

This second solution is better practice because you are not rendering the JS with Django which means it can be moved to an external file.

👤aumo

Leave a comment