Django Admin List Filter Remove All Option

Viewed 2376

As you can see from the screenshot bellow, When using and customizing django admin filters like so:

class DealExpiredListFilter(admin.SimpleListFilter):
  title = 'expired'

  parameter_name = 'expired'

  def lookups(self, request, model_admin):
      return (
          ('yes', 'yes'),
          ('no', 'no'),
      )

  def queryset(self, request, queryset):
      if self.value() == "yes":
          return queryset.filter(end_date__lt=timezone.now())
      elif self.value() == "no":
          return queryset.exclude(end_date__lt=timezone.now())

Django will insert an "All" option at any case (which is great for %99 of the times). I want to rename or remove that "All" option as can bee seen in the screenshot

scrrenshot

1 Answers

I eventually solved it by browsing the source code which can be found [here in this link][1] and overriding the choices function. I only changed the "All" selection to show "Yes" in this code that was added to my filter class :

from django.utils.encoding import force_text

def choices(self, changelist):
    """Copied from source code to remove the "All" Option"""
    yield {
        'selected': self.value() is None,
        'query_string': changelist.get_query_string({}, [self.parameter_name]),
        'display': 'Yes',
    }
    for lookup, title in self.lookup_choices:
        yield {
            'selected': self.value() == force_text(lookup),
            'query_string': changelist.get_query_string({self.parameter_name: lookup}, []),
            'display': title,
        }

As Linh mentioned: For anyone only want to remove the all option just delete 'display': 'Yes', from the first yield{} in choices function [1]: https://github.com/django/django/blob/main/django/contrib/admin/filters.py#L44

Related