Skip to content

Instantly share code, notes, and snippets.

@lprsd
Created June 1, 2011 08:59
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lprsd/1002008 to your computer and use it in GitHub Desktop.
Save lprsd/1002008 to your computer and use it in GitHub Desktop.
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
Copy link

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
Copy link

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
Copy link

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