Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 replace the <li> with a dropdown selection (combobox) or something similar that will solve the same problem.

like image 785
sorin Avatar asked Mar 25 '11 06:03

sorin


People also ask

What is filter dropdown?

Filter dropdowns provide a UI for applying filter criteria against columns in the GridView and its descendants, and against card fields in the CardView and LayoutView. You can choose between four filter dropdown presentation styles. The table below lists the main properties and methods related to this visual element.

Can you filter by property Django?

Django-property-filter is an extension to django-filter and provides functionality to filter querysets by class properties. It does so by providing sub-classes for Filters and Filtersets to keep existing django-filter functionality. For more details and examples check the documentation.


2 Answers

Thanks @beholderrk, @gediminas and @jk-laiho! I packaged this into a reusable app.

Install:

pip install django-admin-list-filter-dropdown 

Enable in settings.py:

INSTALLED_APPS = (     ...     'django_admin_listfilter_dropdown',     ... ) 

Use in admin.py:

from django_admin_listfilter_dropdown.filters import (     DropdownFilter, ChoiceDropdownFilter, RelatedDropdownFilter )  class EntityAdmin(admin.ModelAdmin):     ...     list_filter = (         # for ordinary fields         ('a_charfield', DropdownFilter),         # for choice fields         ('a_choicefield', ChoiceDropdownFilter),         # for related fields         ('a_foreignkey_field', RelatedDropdownFilter),     ) 

Here's what it looks like:

Screenshot of dropdown list filter

like image 200
mrts Avatar answered Sep 29 '22 14:09

mrts


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!

like image 31
Gediminas Avatar answered Sep 29 '22 13:09

Gediminas