Categorized: Django

Use Django’s Permalink Decorator with Generic Views

The permalink decorator is the way to keep your URLs DRY. The only place you need to define where something lives is in your urls.py. In your templates, just point to {{ object.get_absolute.url }}. The problem with how they tell you to do it in the book, the documentation, and elsewhere is that it doesn’t work right if you’re using the same view function more than once in all your urls.py files (which is bound to happen if you’re using a bunch of generic views). That’s because Django has no way of telling which one you mean.

Named URL patterns to the rescue.

If you have a URLpattern that looks like this:

(r'^(?P<slug>[-\w]+)/$', list_detail.object_detail, log_detail),

Change it to this:

url(r'^(?P<slug>[-\w]+)/$', list_detail.object_detail, log_detail, name='log-detail'),

Note the addition of “url” to the start of the line and the “name=” bit at the end.

Now, in your model file(s), do the following:

Add this line to the top of the file:

from django.db.models import permalink

At the bottom of the model class do something similar to this:

@permalink
def get_absolute_url(self):
    return ('log-detail', (), { 'slug': self.slug })

Any other question you have about this stuff is probably in the other sources.

Sources:

Comments

Stefan → April 6th, 2008 at 11:34 am

Thank you very much! This was exactly the thing I was searching for. Your blog is in my feeds now. Very good stuff!

What do you think about that?

Elsewhere in the empire: Home, Blog, APOD