Django Upgrade Quickhack — Adding quotes to url template tags.

Over the past few days, I have been busy upgrading a few libraries we were using to gain much needed new functionality. Amongst those is upgrading DJango 1.4 to 1.6 to get the new User model as well as be able to drop the PGBouncer dependancy because DJango 1.6 supports persistent database connections. Unfortunately, as of Django 1.5, the url template tag requires the argument to be a string or context variable, which means I have to scour through a few hundred templates and change tags from something like {% url post post.slug %} to {% url “post” post.slug %}. Well, instead of doing that, here is a handy regular expression to do the replacement for us: s/(\{% url[\s]+?)([^"'\s][^\s]+)/$1'$2'/g.

Breaking it down

  • \{ Match the opening bracket, note that we need to escape it
  • %url Match the characters exactly as is
  • [\s]+? Match any whitespace character one or more times. This concludes our first capture group
  • [^"'\s] Match the first character that is not a quote or a space
  • [^\s]+ Keep matching one or more characters as long as they are not a whitespace. This could actually be turned to match alphanumerics and dashes instead. This ends our first capture group
  • $1'$2' Replace the first capture group with an exact copy of itself, then insert a quote then the second capture group and then another quote

This regex saved me from spending half a day going file by file.