Justin Duke

Getting the admin link for an object in Django

You’re probably familiar with Django’s get_absolute_url method (docs here) that lets you hook up a Model instance to a specific URL.

This is really nice because instead of having to do something like this:

<a href="/people/{{ object.id }}/">{{ object.name }}</a>

You can do something like this:

<a href="{{ object.get_absolute_url }}">{{ object.name }}</a>

This lets you have a single source of truth tying an instance to its detail URL, meaning that if the URL configuration ever changes you only have to change it in one place.

The same use case and reasoning is also true of generating admin URLs for internal use!

All you have to do is include this snippet:

class MyModel(models.Model):

    def get_admin_url(self):
        content_type = ContentType.objects.get_for_model(self.__class__)
        return urlresolvers.reverse("admin:%s_%s_change" % (content_type.app_label, content_type.model), args=(self.id,))

And you’re good to go. Now, you can refer to this as follows:

<a href="{{ object.get_admin_url }}">{{ object.name }}</a>

And get a link to edit that object in Django’s internal admin.

Liked this post? You should subscribe to my newsletter and follow me on Twitter.

(I've got an RSS feed, too, if you'd prefer.)