[Django]-Django Admin Custom Change List Arguments: Override /?e=1

7πŸ‘

βœ…

I think you just need to put your custom filter fields in the search_fields class variable as outlined in the Advanced Search Django Snippet.

You should be able to modify the snippet to support date ranges as well.

πŸ‘€dan-klasson

7πŸ‘

I know this is an old post, but just ran into a need for this and discovered a very short and simple solution that I thought I would share. Key here is to make a filter that doesn’t affect the queryset and accepts anything passed to it in the lookups as valid option. Something like the following:

from django.contrib.admin import SimpleListFilter    

class PassThroughFilter(SimpleListFilter):
    title = ''
    parameter_name = 'pt'
    template = 'admin/hidden_filter.html'

    def lookups(self, request, model_admin):
        return (request.GET.get(self.parameter_name), ''),

    def queryset(self, request, queryset):
        return queryset

The hidden_filter template is blank to prevent adding anything to the filter area, and the lookups method will always return whatever I have entered for the pt parameter as a valid filter entry. This will prevent the ?e=1 error from popping up as the page loads.

This can be reused with any admin, using the pt parameter. If you need to pass multiple parameters for a single admin, then just subclass this into separate filters and override parameter_name with whatever parameters you need. This will have the effect of allowing those parameters in the query string without affecting the queryset or showing up in the filter column, and you can then use them for whatever purpose you needed them elsewhere.

Hope this helps someone down the road.

5πŸ‘

In summary, here is the undocumented hack used above:

set request.GET._mutable = True, then request.GET.pop() off the custom GET argument(s) you are using.

0πŸ‘

I have simplified accepted solution This will not work as ModelAdmin instance is reused between requests and self.active_pp stores previous value for e.g. change_view request:

class FeaduredAdmin(admin.ModelAdmin):
    ...

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        if self.active_pp:
            qs = qs.filter(...)
        return qs

    def changelist_view(self, request, extra_context=None):
        if request.GET:
            request.GET._mutable=True
            try:
                self.active_pp = request.GET.pop('pp')[0]
            except KeyError:
                self.active_pp = None
            request.GET_mutable=False
        return super().changelist_view(request, extra_context=extra_context)

This solution intentionally makes pp not participate in other admin filters. If you need pp to be honored by other filters use @meesterguyperson solution.

Leave a comment