开发者

For a django model, how can I get the django admin URL to add another, or list objects, etc.?

开发者 https://www.devze.com 2023-02-14 17:20 出处:网络
As much as I love the django documentation, the section on bookmarklets in the admin is strangely vague.

As much as I love the django documentation, the section on bookmarklets in the admin is strangely vague.

My question is this: If I'm in a view and I have a django model (or, in some cases开发者_C百科, an actual object), how can I get to the relevant admin pages for that model (or object)? If I have the object coconut_transportation.swallow.objects.all()[34], how can I jump right to the admin page to edit that particular swallow?

Likewise, how can I get the URL for the admin page to add another swallow?


http://docs.djangoproject.com/en/dev/ref/contrib/admin/#reversing-admin-urls

obj = coconut_transportation.swallow.objects.all()[34]

# list url
url = reverse("admin:coconut_transportation_swallow_changelist")

# change url
url = reverse("admin:coconut_transportation_swallow_change", args=[obj.id])

# add url
url = reverse("admin:coconut_transportation_swallow_add")


You can retrieve this from the actual object instance, this worked for me:

from django.core import urlresolvers
from django.contrib.contenttypes.models import ContentType

content_type = ContentType.objects.get_for_model(object.__class__)
object_admin_url = django.core.urlresolvers.reverse("admin:%s_%s_change" % (content_type.app_label, content_type.model), args=(object.pk,))

See this: http://djangosnippets.org/snippets/1916/


You can actually retrieve the info without making a query to ContentTypes

Just add this to your model class:

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

精彩评论

暂无评论...
验证码 换一张
取 消