Reputation: 33
Before you mark this as Duplicate, I have read the solutions to this question.
In Django Admin I have lots of values. The team that works on that data, currently can use CTRL+F to atleast find the required field.
To fix the UI I have the Dropdown rendering option available in the solution of the question tagged above. But, as I said I need it to be searchable.
Upvotes: 3
Views: 1756
Reputation: 121
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.
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
class CarCompany(models.Model):
name = models.CharField(max_length=128)
class CarModel(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
class CarCompanyFilter(AutocompleteFilter):
title = 'Company' # display title
field_name = 'company' # name of the foreign key field
class CarCompanyAdmin(admin.ModelAdmin):
search_fields = ['name'] # this is required for django's autocomplete functionality
# ...
class CarModelAdmin(admin.ModelAdmin):
list_filter = [CarCompanyFilter]
# ...
After following these steps you may see the filter as:
auto_complete
functionailty), so as long as the Django version you are using is greater than 2.0, you should be fine.list_filters
you may have, like change the Title above the dropdown, or a custom Search logic etc.str(obj)
Upvotes: 3