0

我有一个模型方法_get_admin_url,想动态构建 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 和类名的值?或者,还有更好的方法?

4

2 回答 2

1

您可以使用该Reversing admin URLs功能

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))
于 2013-10-01T16:33:09.607 回答
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 和 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/'
于 2013-10-02T21:52:58.140 回答