Django管理员 - 自定义更改列表视图

问题描述:

我需要向Django管理员添加自定义视图。这应该与某个模型的标准ChangeList视图相似,但具有自定义结果集。 (我需要显示所有具有日期的其他日期少于今天的模型,但这并不真正相关)。

I need to add a custom view to the Django Admin. This should be similar to a standard ChangeList view for a certain model, but with a custom result set. (I need to display all models having some date or some other date less than today, but this is not really relevant).

单向我可以这样做是通过使用Admin queryset 方法,如

One way I can do this is by using the Admin queryset method, like

class CustomAdmin(admin.ModelAdmin):
    ...
    def queryset(self, request):
        qs = super(CustomAdmin, self).queryset(request)
        if request.path == 'some-url':
            today = date.today()
            # Return a custom queryset
        else:
            return qs

这确保...

问题是我不知道如何将 some-url 绑定到标准的ChangeList视图。

The problem is that I do not know how to tie some-url to a standard ChangeList view.

所以你想要一个第二个URL转到更改列表视图,以便您可以检查所请求的URL中的哪一个,然后相应地更改查询集?
只需模拟django.contrib.admin.options所做的并添加另一个URL到ModelAdmin。

So you want a second URL that goes to the changelist view so you can check which of the two it was by the requested URL and then change the queryset accordingly? Just mimick what django.contrib.admin.options does and add another URL to the ModelAdmin.

应该如下所示:

class CustomAdmin(admin.ModelAdmin):

    def get_urls(self):
        def wrap(view):
            def wrapper(*args, **kwargs):
                kwargs['admin'] = self   # Optional: You may want to do this to make the model admin instance available to the view
                return self.admin_site.admin_view(view)(*args, **kwargs)
            return update_wrapper(wrapper, view)

        # Optional: only used to construct name - see below
        info = self.model._meta.app_label, self.model._meta.module_name

        urlpatterns = patterns('',
            url(r'^my_changelist/$',   # to your liking
                wrap(self.changelist_view),
                name='%s_%s_my_changelist' % info)
        )
        urlpatterns += super(CustomAdmin, self).get_urls()
        return urlpatterns