Here is my general solution using redirection, it just checks if there are any GET parameters, if they do not exist, then it is redirected with the default get parameter. I also have a list_filter set, so it selects this and displays the default value.
from django.shortcuts import redirect class MyModelAdmin(admin.ModelAdmin): ... list_filter = ('status', ) def changelist_view(self, request, extra_context=None): referrer = request.META.get('HTTP_REFERER', '') get_param = "status__exact=5" if len(request.GET) == 0 and '?' not in referrer: return redirect("{url}?{get_parms}".format(url=request.path, get_parms=get_param)) return super(MyModelAdmin,self).changelist_view(request, extra_context=extra_context)
The only caveat is when you do direct access to the page using ?? is present in the url, there is no HTTP_REFERER, so it will use the default parameter and redirect. This is great for me, it works great when you click through the admin filter.
UPDATE
To get around the caveat, I ended up writing a custom filter function that simplified the changelist_view function. Here is the filter:
class MyModelStatusFilter(admin.SimpleListFilter): title = _('Status') parameter_name = 'status' def lookups(self, request, model_admin):
And now changelist_view only passes the default parameter if it is missing. The idea was to get rid of the ability of generics filters to view all without using get parameters. To view everything, for this purpose I assigned status = 8 .:
class MyModelAdmin(admin.ModelAdmin): ... list_filter = ('status', ) def changelist_view(self, request, extra_context=None): if len(request.GET) == 0: get_param = "status=5" return redirect("{url}?{get_parms}".format(url=request.path, get_parms=get_param)) return super(MyModelAdmin, self).changelist_view(request, extra_context=extra_context)
radtek Sep 11 '14 at 15:23 2014-09-11 15:23
source share