Apply default filters in admin

瀏覽次數:167 次
跳到第一則未讀訊息

Nate Granatir

未讀,
2017年4月24日 中午12:12:182017/4/24
收件者: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

未讀,
2017年4月24日 下午6:31:182017/4/24
收件者: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

未讀,
2017年4月24日 晚上7:08:332017/4/24
收件者:Django users
Where would I put that code? Is there a way to do it when the Admin form is initialized?

Todor Velichkov

未讀,
2017年4月26日 清晨7:37:322017/4/26
收件者: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

未讀,
2017年4月27日 下午5:48:042017/4/27
收件者:Django users
That worked! Thanks!!

Nate
回覆所有人
回覆作者
轉寄
0 則新訊息