Django view returns a string that does not display correctly in the html template

The view I'm using returns a string in an html template. The returned string contains special characters that are not displayed correctly in the template. Simply put, the string returned from the view might look like this:

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

And displayed in the html template as follows:

 & quot;Foo bar& quot; 

How can I fix the encoding so that it displays correctly?

+4
source share
2 answers

Use a safe filter when printing:

 {{ test|safe }} 

Or do it in a view:

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

Note that by doing this, you are telling Django that the contents of the string are safe and do not require HTML escaping. If you plan on putting anything that might come from the user, that would leave you vulnerable to XSS attacks, so use them with caution.

+12
source

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

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

In general, if you are surprised at such elementary and well-documented features of Django, it may be time to stop coding for a while and catch the reading and understanding.

0
source

All Articles