How to change the Django admin filter to use a dropdown instead of list?

后端 未结 9 866
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-13 03:58

If, for a field that you want to filter by, you have more than ~10 values, the filtering sidebar starts to be ugly and harder to use.

I\'m looking for a solution to

9条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-13 04:29

    I cannot comment answers so I'll add to beholderrk's answer here.

    1. create a new template called dropdown_filter.html or similar
    2. copy the code of filter.html from feincms to dropdown_filter.html
    3. create a new filter class in filters.py:

      from django.contrib.admin.filters import AllValuesFieldListFilter
      
      class DropdownFilter(AllValuesFieldListFilter):
          template = 'admin/dropdown_filter.html'
      
    4. now you can use this filter in your admin class:

      class SomeAdmin(admin.ModelAdmin):
          # ...
          list_filter = (('country', DropdownFilter),)
      

    Works great!

提交回复
热议问题