The default filter in the admin site

Is there a way to set the default value for the filter in the admin site?

Class Account(models.model): isClosed = models.BooleanField(blank=True) name = models.CharField(core=True, max_length=255,unique=True) 

In admin.py:

 class Admin(admin.ModelAdmin): list_filter = ['isClosed'] 

On the admin page, I want the default value for the isClosed field to be no, not all.

Thanks.

+6
source share
1 answer

You need to create a custom list filter that inherits from django.contrib.admin.filters.SimpleListFilter and filters by default open accounts. Something in this direction should work:

 from datetime import date from django.utils.translation import ugettext_lazy as _ from django.contrib.admin import SimpleListFilter class IsClosedFilter(SimpleListFilter): title = _('Closed') parameter_name = 'closed' def lookups(self, request, model_admin): return ( (None, _('No')), ('yes', _('Yes')), ('all', _('All')), ) def choices(self, cl): for lookup, title in self.lookup_choices: yield { 'selected': self.value() == lookup, 'query_string': cl.get_query_string({ self.parameter_name: lookup, }, []), 'display': title, } def queryset(self, request, queryset): if self.value() == 'closed': return queryset.filter(isClosed=True) elif self.value() == None: return queryset.filter(isClosed=False) class Admin(admin.ModelAdmin): list_filter = [isClosedFilter] 
+10
source

Source: https://habr.com/ru/post/944891/


All Articles