The following code in one of my views returns unescaped html string which cannot be parsed in frontend since it is an Ajax request.
return render_to_response(template_name, {
'form': form,
redirect_field_name: redirect_to,
'site': current_site,
'site_name': current_site.name,
}, context_instance=RequestContext(request))
What is the simplest way to correct this ? Thanks in advance..
For example, you can check if my_textfield contains a script tag. If so, mark the instance as malicious and return an escaped version of my_textfield (the normal Django behavior). Otherwise, use mark_safe to return your HTML code marked as safe. And all of this doesn't need any migrations to the database.
The escape filter escapes HTML characters from the value. Note: Escaping HTML characters is a default setting in Django, so we have to turn off autoescape in the example to be able to see the difference.
Escaping in HTML means, that you are replacing some special characters with others. In HTML it means usally, you replace e. e.g < or > or " or & . These characters have special meanings in HTML. Imagine, you write <b>hello, world</b> And the text will appear as hello, world.
This flag tells Django that if a “safe” string is passed into your filter, the result will still be “safe” and if a non-safe string is passed in, Django will automatically escape it, if necessary. You can think of this as meaning “this filter is safe – it doesn't introduce any possibility of unsafe HTML.”
Lakshman Prasad's answer is technically correct, but a bit cumbersome. A better way to escape text would be (as suggested in a comment by miku above):
from django.utils.html import escape
return HttpResponse(escape(some_string))
To return just plain HTML to the client from within your view, use django.http.HttpResponse
from django.http import HttpResponse
def view(request)
# Do stuff here
output = '''
<html>
<head>
<title>Hey mum!</title>
</head>
</html>'''
return HttpResponse(output)
To prevent the Django templating system from escaping HTML in a template, just use the |safe
filter:
response = "<img src='cats.png'/>"
# Meanwhile, in the template...
<div id="response">
{{response|safe}}
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With