views:

200

answers:

3

I need the html returned using render_to_response to be escaped. I am unable to find any suitable documentation. Can someone point in some direction ?

the code is :

return render_to_response(template_name, {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))

Here I need the response html text to be escaped. I way I know is reading template file in string and escaping it with re.escape() and then rendering it. whats a cleaner and simpler way to do that ??

+2  A: 

String passed from the views to the templates via render_to_response are escaped by default.

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

By default in Django, every template automatically escapes the output of every variable tag. Specifically, these five characters are escaped:

< is converted to &lt;
> is converted to &gt;
' (single quote) is converted to &#39;
" (double quote) is converted to &quot;
& is converted to &amp;

Again, we stress that this behavior is on by default.

The MYYN
+1  A: 

You can use the escape template filter or the autoescape template tag. See http://docs.djangoproject.com/en/dev/ref/templates/builtins/

luc
+2  A: 

It sounds like you want the entirety of the response to be escaped -- is that true? It seems a little odd, but you can certainly do it.

import django.utils.html as html
string = render_to_string(<all of the args to render_to_response>)
escaped_string = html.escape(string)
return HttpResponse(escaped_string)

I'm not quite sure what the person/browser on the other end would do with this, but it sounds like what you were asking for.

Peter Rowell