Apply default filters in admin

160 views
Skip to first unread message

Nate Granatir

unread,
Apr 24, 2017, 12:12:18 PM4/24/17
to Django users
In my app I have admin filters for a field called "language" - language is a field in several of my models - and I've created them custom, inheriting from SimpleListFilter, so that I can apply a default of English when none has yet been specified. This works almost perfectly - the only problem is that if I do it this way, by altering the queryset in the admin filter when the user has not selected an option, the parameter is not displayed to the user in the GET paramaters of the URL, which I worry is confusing to the user. 

Is there any way to solve this problem? Essentially I want to apply a default admin filter and have that filter appear in the URL as if it were chosen by the user. I am open to alternative solutions if anyone has done something like this before, even if it means a solution other than using a custom admin filter (e.g. some way of applying default GET parameters before the request is passed to the admin page.)

Thanks.

Todor Velichkov

unread,
Apr 24, 2017, 6:31:18 PM4/24/17
to Django users
I think a simple redirect can fix your problem.

Something like this:

if 'lang' not in request.GET:
    q
= request.GET.copy()
    q
.setdefault('lang', 'en')
   
return redirect('%s?%s' % (request.path, q.urlencode()))

Nate Granatir

unread,
Apr 24, 2017, 7:08:33 PM4/24/17
to Django users
Where would I put that code? Is there a way to do it when the Admin form is initialized?

Todor Velichkov

unread,
Apr 26, 2017, 7:37:32 AM4/26/17
to Django users
I think `ModelAdmin.changelist_view` is the right place.

class MyModelAdmin(admin.ModelAdmin):
   
def changelist_view(request, extra_context=None):

       
if 'lang' not in request.GET:
            q
= request.GET.copy()
            q
.setdefault('lang', 'en')
           
return redirect('%s?%s' % (request.path, q.urlencode()))

       
return super(MyModelAdmin, self).changelist_view(
            request
, extra_context=extra_context,
       
)



Nate Granatir

unread,
Apr 27, 2017, 5:48:04 PM4/27/17
to Django users
That worked! Thanks!!

Nate
Reply all
Reply to author
Forward
0 new messages