Automatically generating admin URLs for your objects

It's very easy to generate URLs to your django models using get_absolute_url(), but you can also use this pattern to just as easily create URLs to the admin page for your django models too. This post shows you how to make a get_admin_url() model method that generates links to give you quick access to your admin.

Most Django developers are familiar with how easy it is to generate URLs for you objects using get_absolute_url() - you simply create a model method that reverses the object's 'detail' url. The Django docs also outline how to easily reverse admin URLs for model instances allowing you to quickly generate links to the backend of your app.

A nice extension of these principles is to create a get_admin_url() model method that automatically generates the reversed admins URL:

> book = Book.objects.get(pk=1)
> print(book.get_admin_url())
> "/admin/library/book/1/"

The method itself can be implemented as a model mixin meaning you can easily reuse this in numerous models:

from django.contrib.contenttypes.models import ContentType
from django.core.urlresolvers import reverse
 
class AdminURLMixin(object):
    def get_admin_url(self):
        content_type = ContentType.objects.get_for_model(self.__class__)
        return reverse("admin:%s_%s_change" % (
            content_type.app_label,
            content_type.model),
            args=(self.id,))
 
 class Book(models.Model, AdminURLMixin):
     ...

or if you perfer using the permalink decorator:

from django.contrib.contenttypes.models import ContentType
from django.db import models
 
class AdminURLMixin(object):
    @models.permalink
    def get_admin_url(self):
        content_type = ContentType \
            .objects \
            .get_for_model(self.__class__)
        return ('admin:%s_%s_change' % (
            content_type.app_label,
            content_type.model), [str(self.id)])