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.
[1] https://docs.djangoproject.com/en/1.3/ref/utils/#django.utils.safestring.SafeUnicode
Share
Tags
Similar Articles
Another day, another Zero Day: What all Digital Development organizations should take away from recent IT security news
Even if you don’t work as a software developer, you probably heard about recent, high profile security issues that had IT Admins and developers frantically patching servers over the holidays and again more recently. Dimagi's CTO shares what these recent issues mean for Digital Development organizations.
Technology
January 28, 2022
Join the fight to support critical open source infrastructure
Open Source tools are a critical piece of global infrastructure, and need champions for long term investment
Technology
March 17, 2020
Two big lessons that Iowa and Geneva can teach us about technology in digital development
Last week brought two high profile technology failures into the global spotlight. Although these two mishaps may seem quite different at first glance, they both highlight challenges that are inherent in providing software in the public sector (regardless of locale) and illustrate cautionary lessons worth discussing for practitioners in Digital Development. The Iowa Caucus Debacle
Technology
February 7, 2020