In Django, how do I get escaped html in HttpResponse?

The following code in one of my views returns an unescaped html string that cannot be parsed in the interface, as this 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 easiest way to fix this? Thanks in advance.

+7
python django escaping django-templates
source share
3 answers

Lakshman Prasad's answer is technically correct, but a bit cumbersome. The best way to avoid the text would be (as stated in the miku comment above):

 from django.utils.html import escape return HttpResponse(escape(some_string)) 
+17
source

To return only plain HTML to the client from 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 template system from escaping HTML in the template, use the |safe filter:

 response = "<img src='cats.png'/>" # Meanwhile, in the template... <div id="response"> {{response|safe}} </div> 
+5
source

It should go by default.

But, if you want, you can explicitly force the screen.

 from django.utils.safestring import mark_for_escaping return HttpResponse(mark_for_escaping(loader.render_to_string(""""Render Response Syntax""")) 
+1
source

All Articles