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:
You can do something like this:
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:
And get a link to edit that object in Django’s internal admin.