over 7 years ago

When django template renders parameters passed from views, it auto escapes characters that are considered as HTML entities.In English, that means characters like the double quote is convereted to ". This default behavior may not be what you want so it is important to know how to turn it off.

Here is a situation that I encountered while working on a project. I need to pull all of the staffusers out of the database and then put their email addresses in the following format:

[{'email': 'user1@blah.com'}, {'email': 'user2@blah.com'}, ...]

In the view function, I pull the email addresses out of the database and converted them into JSON format:

def a_view_handler(request):
  contacts = User.objects.get(is_staff=True)
  email_list = []
  for c in contacts:
      if c.email:
          email_list.append({'email': c.email})
  return render(request, 'contacts.html', {'email_list': json.dumps(email_list)}

Then, in the template:

emails = {{ email_list }}

When I tested the page, this is what I see:

emails = [{"email": "test@test.com"}, ...]

This happened because when python converts the email_list to json, it added double quotes around the key and value pairs. When Django template renders it, it auto escaped the double quote character (meaning convert it to #quot;). To stop Django from doing that:

{% autoescape off %}
    emails = {{ email_list }}
{% endautoescape %}

The autoescape block controls whether the content inside of it should be auto escaped or not. So use it when you dont want to see those HTML entities.

← The netstat command line arguments Django SMTP AUTH extension not supported by server →
comments powered by Disqus