Login

Get admin url for a model

Author:
timbroder
Posted:
February 9, 2010
Language:
Python
Version:
1.1
Score:
4 (after 4 ratings)

Add this to your model to be able to get their admin change link from anywhere

Useful if you want to jump to the admin screen of an object you are looking at on the front end

1
2
3
4
5
6
from django.core import urlresolvers
from django.contrib.contenttypes.models import ContentType

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,))

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 12 months ago

Comments

s29 (on October 27, 2010):

Nice. Minor tweak, args=(self.pk,) instead, to support models with explicit primary_key.

#

twoolie (on August 15, 2012):

You can do it without using a query to ContentTypes!

def get_admin_url(self):
    return urlresolvers.reverse("admin:%s_%s_change" %
        (self._meta.app_label, self._meta.module_name), args=(self.id,))

#

abulka (on March 16, 2016):

@twoolie Your solution doesn't work for me, only the original solution works. Because in my model, self._meta.module_name doesn't exist.

#

stodge (on May 31, 2016):

self._meta.module_name should be self._meta.model_name.

#

Please login first before commenting.