How to: Use Django HTML utils

I’ll often see things like this:

username_in_html = u'<a href="%s">%s</a>' % (link, username)

While it’s not super great to be generating HTML in Python code all over the place, there are times where that’s the simplest and cleanest thing to do. Even in those cases, the above line should leave you a little queasy. For one, what if the value of link happened to be

u'">YOU GOT HACKED</a><script>/* Evil stuff */</script><a href="'

or whatever? Then to the more anal among us, it’s annoying to then have to go everywhere we’d previously used {{ username_in_report }} and change it to {{ username_in_report|safe }} once you realize that it needs to have some html thrown in.

There are some really nice Django conventions and utilities for dealing with exactly this, and I think we should start using them as a matter of policy. They center around SafeUnicode [1] and its little friends mark_safe and escape in django.utils.html. You could replace the above line with

username_in_html = mark_safe(u'<a href="%s">%s</a>' % (escape(link), escape(username)))

Using escape will protect against html injection, and mark_safe will make it so you don’t have to pipe it through the “safe” filter in your template.

I suggest we always wrap an html string with mark_safe as a matter of style and when you do so to carefully consider which pieces need to be escaped.




Similar Articles

The World's Most Powerful Mobile Data Collection Platform

Start a FREE 30-day CommCare trial today. No credit card required.

Get Started

Learn More

Get the latest news delivered
straight to your inbox