Django Admin - Custom changelist view

2019-04-09 04:24发布

问题:

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).

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

This makes sure that ...

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

回答1:

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.

Should look something like this:

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