← Updated: Local Django Sprint, Berlin, ...

newcomments are in trunk →

Easy overrides for absolute URLs of reusable apps

Welcome to the new jannisleidel.com, after finally being migrated from Wordpress to Django. I’m now a happy user of James Bennett’s Coltrane app. It provides the features I used in the old Wordpress installation and is simple enough to be hacked in the spare time. One thing though was new to me and I want to share this little piece of usefulness with you.

By default Coltrane uses a URL scheme for the weblog entries like:

r'^(?P<year>\d{4})/(?P<month>\w{3})/(?P<day>\d{2})/(?P<slug>[-\w]+)/$'

If you want to change that URL scheme without modifying Coltrane you can fairly easily override the provided URLconf with your own. For example I’m using the following regular expression here:

r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<slug>[-\w]+)/$'

But this is only half the battle. Furtunately, Coltrane uses absolute URLs for the entry models. And this is when a special setting needs to be brought into play: ABSOLUTE_URL_OVERRIDES — “A dictionary mapping “app_label.model_name” strings to functions that take a model object and return its URL.”

Combined with the reverse() utility it’s a nice, small solution, you can put in the settings.py file of your site:

from django.core.urlresolvers import reverse
ABSOLUTE_URL_OVERRIDES = {
    'coltrane.entry': lambda o: reverse('coltrane_entry_detail', kwargs={
                                            'year': o.pub_date.strftime('%Y'),
                                            'month': o.pub_date.strftime('%m'),
                                            'slug': o.slug }),
}

Django Aug. 21, 2008, 4:03 p.m. comments (3)

comments

Thorsten Aug. 21, 2008, 5:11 p.m.

Hi, this is very useful, thanks for posting!

James Bennett Aug. 22, 2008, 4:42 a.m.

You don't have to use the provided URLConf, you know :)

Jannis Leidel Aug. 22, 2008, 10:26 a.m.

Oh sure, and I don't use the provided URLconf :)

But unless I'm totally blind I still need to somehow override the get_absolute_url() of the entry objects so it contains the month as a number, not as short slug.