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

19,069

Solution 1

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))

Solution 2

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>

Solution 3

It should escape by default.

But, if you want to, you can explicitly force escaping.

from django.utils.safestring import mark_for_escaping
return HttpResponse(mark_for_escaping(loader.render_to_string(""""Render Response Syntax"""))
Share:
19,069

Related videos on Youtube

Nullpoet
Author by

Nullpoet

Updated on July 20, 2020

Comments

  • Nullpoet
    Nullpoet almost 4 years

    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..

  • Nullpoet
    Nullpoet over 14 years
    Django is not autoescaping the response which I have confirmed using firebug. I need it to be escaped.
  • Aether McLoud
    Aether McLoud over 14 years
    So, you want <p> to change to &lt;p&gt;?, or stay as <p>?

Related