如何在Django 1.5中反转自定义管理URL?

时间:2013-09-04 12:08:18

标签: python django django-admin django-urls

我想为ModelAdmin添加自定义网址,但似乎Django在1.5中更改了模板语法。我尝试了这种方式,因为文档指出但不幸的是它不起作用。

class VariableAdmin(admin.ModelAdmin):

    def get_urls(self):
         urls = super(VariableAdmin, self).get_urls()
         my_urls = patterns('',
                       url(r'^settings/([A-Za-z0-9]*)', self.admin_site.admin_view(self.settings), name="settings"))
         return my_urls + urls

    def settings(self, request, category):
         return render_to_response('variables.html', {"opts": Variable._meta}))

这是我的variables.html

{% load admin_urls %}
{% url opts|admin_urlname:'settings' %}

此代码抛出如下错误:

Reverse for 'common_variable_settings' with arguments '()' and keyword arguments '{}' not found.

如何解决此问题?

1 个答案:

答案 0 :(得分:2)

尝试更改视图名称以包含应用程序和型号名称:

...
my_urls = patterns('', url(r'^settings/([A-Za-z0-9]*)',
                   self.admin_site.admin_view(self.settings), 
                   name="common_variable_settings"))
...

admin_urlname模板过滤器返回“完整”名称,请参阅其源代码:

@register.filter
def admin_urlname(value, arg):
    return 'admin:%s_%s_%s' % (value.app_label, value.module_name, arg)

所以你肯定需要为你的观点命名"appname_modulename_settings"。也许然后尝试将正则表达式改为这样的东西:

r'^settings/([A-Za-z0-9]+/)?$'