How To Change The Django Admin Filter To Use A Dropdown Instead Of List That Can Also Be Searched?
Solution 1:
I was struggling with the same problem some few weeks back. So this answer might be useful to some developers from the future.
I managed to solve the problem by writing a custom template.html
I have bundled the code in an amazing package now that does the same for you, here's the link.
Here's how you can implement a Searchable Dropdown in place of the default List:
1. Installation:
pip install django-admin-searchable-dropdown
This command will install the latest version of the package in your project.
Now, include the package in your project by adding admin_searchable_dropdown
to your INSTALLED_APPS
inside settings.py
file.
2. Usage: Let's say you have following models:
from django.db import models
classCarCompany(models.Model):
name = models.CharField(max_length=128)
classCarModel(models.Model):
name = models.CharField(max_length=64)
company = models.ForeignKey(CarCompany, on_delete=models.CASCADE)
And you would like to filter results in CarModelAdmin
on the basis of company
. You need to define search_fields
in CarCompany
and then define filter like this:
from django.contrib import admin
from admin_searchable_dropdown.filters import AutocompleteFilter
classCarCompanyFilter(AutocompleteFilter):
title = 'Company'# display title
field_name = 'company'# name of the foreign key fieldclassCarCompanyAdmin(admin.ModelAdmin):
search_fields = ['name'] # this is required for django's autocomplete functionality# ...classCarModelAdmin(admin.ModelAdmin):
list_filter = [CarCompanyFilter]
# ...
After following these steps you may see the filter as:
- This is how the list filter is rendered in the form of a dropdown when the package is used
- And the dropdown filter is also Searchable
Features Offered:
- If you have large fields in Admin Filter, the sidebar gets widened, this package provides you the same list in a dropdown format, hence, no such hassle.
- If you have more than, say 20, field items, list filter is now a long side-pane, just ruining the admin interface. The Dropdown filter fixes that.
- The Dropdown is also "Searchable", with an input text field (which utilizes Django's own
auto_complete
functionailty), so as long as the Django version you are using is greater than 2.0, you should be fine. - You can customize other
list_filters
you may have, like change the Title above the dropdown, or a custom Search logic etc. - You can customize Widget Texts to display in the Dropdown Option to use something other than the default
str(obj)
Post a Comment for "How To Change The Django Admin Filter To Use A Dropdown Instead Of List That Can Also Be Searched?"