6

Is there a way of setting the default value for a 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.

Blainn
  • 113
  • 1
  • 6
  • There is a problem with the answer, when you press show all when you don't want to apply the filter, it still apply the filter – Blainn May 13 '13 at 15:46

1 Answers1

16

You'd need to create a custom list filter, inheriting from django.contrib.admin.filters.SimpleListFilter and filtering on unclosed accounts by default. Something along these lines 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() is None:
            return queryset.filter(isClosed=False)


class Admin(admin.ModelAdmin):
    list_filter = [isClosedFilter]
Paolo Melchiorre
  • 5,716
  • 1
  • 33
  • 52
Greg
  • 9,963
  • 5
  • 43
  • 46
  • Great solution. I'll addon. That if you're using this with other list filters you'll want to do the following: `list_filter = ((isClosedFilter), ('date_created', admin.DateFieldListFilter),)` – raiderrobert Jan 19 '16 at 19:46