Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable HTML encoding when using Context in django

In my django application I am using a template to construct email body, one of the parameters is url, note there are two parametes separated by ampersand in the url.

t = loader.get_template("sometemplate")
c = Context({
   'foo': 'bar',
   'url': 'http://127.0.0.1/test?a=1&b=2',
})
print t.render(c)

After rendering it produces: http://127.0.0.1/test?a=1&b=2

Note the ampersand is HTML encoded as "&". One way around the problem is to pass each parameter separately to my template and construct the url in the template, however I'd like to avoid doing that.

Is there a way to disable HTML encoding of context parameters or at the very least avoid encoding of ampersands?

like image 582
Sergey Golovchenko Avatar asked Oct 26 '08 00:10

Sergey Golovchenko


People also ask

How do you turn off Django 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.

What does {% %} mean in Django?

{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.

What is escaping in Django?

Escaping is turning non-safe characters - like HTML tags - into escaped versions so that malicious content such as script tags don't ruin your site. Django does this by default on all content rendered in a template from a variable.

What is {% block content %} in Django?

{% block %}{% endblock %}: This is used to define sections in your templates, so that if another template extends this one, it'll be able to replace whatever html code has been written inside of it. Blocks are identified by their name. Usage: {% block content %} <html_code> {% endblock %} .


1 Answers

To turn it off for a single variable, use mark_safe:

from django.utils.safestring import mark_safe

t = loader.get_template("sometemplate")
c = Context({
   'foo': 'bar',
   'url': mark_safe('http://127.0.0.1/test?a=1&b=2'),
})
print t.render(c)

Alternatively, to totally turn autoescaping off from your Python code, use the autoescape argument when initialising a Context:

c = Context({
   'foo': 'bar',
   'url': 'http://127.0.0.1/test?a=1&b=2',
}, autoescape=False)

The How to turn [Automatic HTML escaping] off section of the documentation covers some of the in-template options if you'd rather do it there.

like image 156
Jonny Buchanan Avatar answered Oct 19 '22 04:10

Jonny Buchanan