views:

345

answers:

2

A view I am using returns a string to a html template. The string which is returned contains special characters which are not represented correctly in the template. To put it simply a string which is returned from the view might look like this:

test = "\"Foo bar\""
return render_to_response('index.html', {'test': test})

And is displayed in the html template like this:

& quot;Foo bar& quot;

How can I fix the encoding so it is displayed correctly?

+7  A: 

Use the safe filter when printing:

{{ test|safe }}

Or, do this in the view:

from django.utils.safestring import mark_safe
test = mark_safe("\"Foo bar\"")

Please note that by doing this you are telling Django that the contents of the string are safe and do not need HTML escaping. If you are planning to put anything whatsoever that could come from the user this would then leave you vulnerable to XSS attacks, so use with caution.

Paolo Bergantino
+1  A: 

Your best bet is to consult the Django documentation, which explains this in detail:

http://docs.djangoproject.com/en/dev/topics/templates/#id2

And, in general, if you're being surprised by such basic and well-documented features of Django, it may be time to stop coding for a while and catch on up reading and understanding.

James Bennett