django: generating absolute URLs

As I mentioned earlier, django provides a convenient and highly de-coupled way to manipulate URLs. At the heart of this functionality is django.core.urlresolver.reverse. This function however generates relative URLs e.g. /album/my-first-album/

At See’n'Report, we wanted every user to have a sub-domain so, hitting http://username.seenreport.com takes you to the user profile. But this created a small problem; all the URLs rendered on the profile page were relative. So a link on profile page like /profile/edit/ was treated as http://adilsaleem.seenreport.com/profile/edit/ and not http://seenreport.com/profile/edit/. So we had to generate absolute urls on profile page.

Thanks to my laziness, I decided to not append the domain name to every URL on profile page template. Instead, I sniffed around the django code for 3 hours looking for a single line solution :). It turned out django does provide a single line solution. The solution is the function,

django.core.urlresolvers.set_script_prefix

You can a url prefix to this function and all subsequent calls to reverse and url tag will generate absolute urls. So I placed a middleware like,

from django.core.urlresolvers import set_script_prefix
if subdomain accessed
      set_script_prefix('http://seenreport.com')
else:
      set_script_prefix('')

And there you go, you can now generate absolute URLS with minimum fuss

Related posts:

  1. django: Hacking django object_list to take list of templates
  2. django: How to expire session on browser close
  3. django: How to get model class from model name

One Comment

  1. Lukasz Dziedzia says:

    This is awesome!

    Thank! I’ve been looking for such simple solution for a long time…

    Regards,
    Lukasz

Leave a Reply