Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 567
Nullpoet Avatar asked Dec 22 '09 13:12

Nullpoet


People also ask

How do you turn off Django's automatic HTML escaping for part of a Web page?

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.

What does escape do in Django?

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.

What does HTML escape mean?

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.

What does safe filter do in Django?

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


2 Answers

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))
like image 183
Joel Cross Avatar answered Oct 16 '22 07:10

Joel Cross


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>
like image 38
Josh Hunt Avatar answered Oct 16 '22 08:10

Josh Hunt