如何构造get_admin_url / get app_label和类名?

时间:2013-10-01 16:27:03

标签: django django-models django-admin

我有一个模型方法_get_admin_url,想要动态构建网址。

class Person(models.Model):
    ...

    def _get_admin_url(self):
        "Returns the admin url."
        # return '/admin/some_app/person/%d' %self.id
        return '/admin/%s/%s/%d/' %(..., ..., d)

    admin_url = property(_get_admin_url)

如何获取app_label和类名的值?或者有更好的方法吗?

2 个答案:

答案 0 :(得分:1)

您可以使用Reversing admin URLs feature

from django.core import urlresolvers
c = Choice.objects.get(...)
change_url = urlresolvers.reverse('admin:polls_choice_change', args=(c.id,))

如果您想参考change_list页面,您可以

urlresolvers.reverse('admin:%s_%s_changelist' % (app_label, model_name))

答案 1 :(得分:0)

也可以使用ContentType设置app_name和model_name,参见:https://stackoverflow.com/a/11395481/991572

所以我最终在webapp/models.py

中这样做了
from django.contrib.contenttypes.models import ContentType
from django.core import urlresolvers

class Base(models.Model):
    title = models.CharField(max_length=100)

    def _get_admin_url(self):
        "Returns the admin change view url."
        content_type = ContentType.objects.get_for_model(self.__class__)
        view_name = "admin:%s_%s_change" % (content_type.app_label, content_type.model)
        url = urlresolvers.reverse(view_name, args=(self.id,)) 
        return url

    admin_url = property(_get_admin_url)            

class Book(Base):
    something = models.CharField(max_length=100)

将Base Base和Book注册到管理站点,在shell中创建了一些条目:

In [1]: from webapp.models import *

In [2]: Base.objects.get(pk=1).admin_url
Out[2]: '/admin/webapp/base/1/'

In [3]: Book.objects.get(pk=2).admin_url
Out[3]: '/admin/webapp/book/2/'