How can I change the default filter choice from \'ALL\'? I have a field named as status which has three values: activate, pending and
A bit off-topic but my search for a similar question led me here. I was looking to have a default query by a date (ie if no input is provided, show only objects with timestamp of 'Today'), which complicates the question a bit. Here is what I came up with:
from django.contrib.admin.options import IncorrectLookupParameters
from django.core.exceptions import ValidationError
class TodayDefaultDateFieldListFilter(admin.DateFieldListFilter):
""" If no date is query params are provided, query for Today """
def queryset(self, request, queryset):
try:
if not self.used_parameters:
now = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
self.used_parameters = {
('%s__lt' % self.field_path): str(now + datetime.timedelta(days=1)),
('%s__gte' % self.field_path): str(now),
}
# Insure that the dropdown reflects 'Today'
self.date_params = self.used_parameters
return queryset.filter(**self.used_parameters)
except ValidationError, e:
raise IncorrectLookupParameters(e)
class ImagesAdmin(admin.ModelAdmin):
list_filter = (
('timestamp', TodayDefaultDateFieldListFilter),
)
This is a simple override of the default DateFieldListFilter. By setting self.date_params, it insures that the filter dropdown will update to whatever option matches the self.used_parameters. For this reason, you must insure that the self.used_parameters are exactly what would be used by one of those dropdown selections (ie, find out what the date_params would be when using the 'Today' or 'Last 7 Days' and construct the self.used_parameters to match those).
This was built to work with Django 1.4.10