Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
django admin default filter values
class YourAdmin(ModelAdmin):
def changelist_view(self, request, extra_context=None):
ref = request.META.get('HTTP_REFERER','')
path = request.META.get('PATH_INFO','')
if not ref.split(path)[-1].startswith('?'):
q = request.GET.copy()
q['usertype'] = 'Publisher'
q['user_status__exact'] = 'activated'
request.GET = q
request.META['QUERY_STRING'] = request.GET.urlencode()
return super(BulkMigrationAdmin,self).changelist_view(request, extra_context=extra_context)
@markcerv

This comment has been minimized.

Copy link

@markcerv markcerv commented Feb 27, 2014

I changed it slightly, so as not to hardcode in the parameters, and instead pass them in in the admin view:

class DefaultFilterMixIn(admin.ModelAdmin):
    def changelist_view(self, request, extra_context=None):
        ref = request.META.get('HTTP_REFERER', '')
        path = request.META.get('PATH_INFO', '')
        if not ref.split(path)[-1].startswith('?'):
            q = request.GET.copy()
            # use try/except in case default_filters isn't defined
            try:
                for filter in self.default_filters:
                    key = filter.split('=')[0]
                    value = filter.split('=')[1]
                    q[key] = value
                request.GET = q
            except:
                request.GET = q
            request.META['QUERY_STRING'] = request.GET.urlencode()
        return super(DefaultFilterMixIn, self).changelist_view(request, extra_context=extra_context)

class SomeAdmin(DefaultFilterMixIn):
    default_filters = ['o=2.1', 'open_job__exact=1']
@aarcro

This comment has been minimized.

Copy link

@aarcro aarcro commented Jul 7, 2014

This doesn't work. request.META.get('HTTP_REFERER', '') is page view behind. So the first time you try to change the filter value, you get the defaults again.

@sin5th

This comment has been minimized.

Copy link

@sin5th sin5th commented May 6, 2016

this maybe works better.
when following admin navigation, the filter will become effective.
when open the url directly, the filter will not work.

def changelist_view(self, request, extra_context=None):
ref = request.META.get('HTTP_REFERER', '').split('?')[0]
if ref and not ref.endswith(request.path):
...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment