Package: django-admin-searchable-dropdown
Django Admin Searchable DropdownA Django admin filter implementation that renders as a searchable select field dropdown.Overview:If you have more than twenty values for a field that you want to filter by in
Django admin, the filtering sidebar gets long, cluttered, sometimes wide and hence, hard to use.This app contains theAutocompleteFilterclass that renders as a drop-down in the
filtering sidebar that can be searched to avoid this problem.Requirements:Requires Django version >= 2.0Features:Custom search view/endpoint (more details)list_filterFilter Factory support (more details)Custom widget text (more details)Support forGrappelliInstallation:You can install it via pip.  To get the latest version clone this repo.pipinstalldjango-admin-searchable-dropdownAddadmin_searchable_dropdownto yourINSTALLED_APPSinside settings.py of your project.Usage:Let's say you have following models:fromdjango.dbimportmodelsclassCarCompany(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 inCarModelAdminon the basis ofcompany.  You need to definesearch fieldsinCarCompanyand then define filter like this:fromdjango.contribimportadminfromadmin_searchable_dropdown.filtersimportAutocompleteFilterclassCarCompanyFilter(AutocompleteFilter):title='Company'# display titlefield_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:Functionality to provide a custom view for search:You can also register your custom view instead of using Django admin'ssearch_resultsto control the results in the autocomplete. For this you will need to create your custom view and register the URL in your admin class as shown below:In yourviews.py:fromadmin_searchable_dropdown.viewsimportAutocompleteJsonViewclassCustomSearchView(AutocompleteJsonView):defget_queryset(self):"""your custom logic goes here."""queryset=CarCompany.objects.all().order_by('name')returnquerysetAfter this, register this view in your admin class:fromdjango.contribimportadminfromdjango.urlsimportpathclassCarModelAdmin(admin.ModelAdmin):list_filter=[CarCompanyFilter]defget_urls(self):urls=super().get_urls()custom_urls=[path('custom_search/',self.admin_site.admin_view(CustomSearchView.as_view(model_admin=self)),name='custom_search'),]returncustom_urls+urlsFinally, just tell the filter class to use this new view:fromdjango.shortcutsimportreversefromadmin_searchable_dropdown.filtersimportAutocompleteFilterclassCarCompanyFilter(AutocompleteFilter):title='Company'field_name='company'defget_autocomplete_url(self,request,model_admin):returnreverse('admin:custom_search')Shortcut for creating filters:It's also possible to use theAutocompleteFilterFactoryshortcut to create
filters on the fly, as shown below. Nested relations are supported too, with
no need to specify the model.AutocompleteFilterFactory('My title', 'field_name')
        AutocompleteFilterFactory('My title', 'fourth__third__second__first')
    Be sure to include distinct in the model admin get_queryset() if the second form is used.
    Assumes: parameter_name == f'fourth__third__second__{field_name}'
        * title: The title for the filter.
        * base_parameter_name: The field to use for the filter.
        * viewname: The name of the custom AutocompleteJsonView URL to use, if any.
        * use_pk_exact: Whether to use '__pk__exact' in the parameter name when possible.
        * label_by: How to generate the static label for the widget - a callable, the name
          of a model callable, or the name of a model field.```

Example:

```python
from django.contrib import admin
from admin_searchable_dropdown.filters import AutocompleteFilterFactory


class AlbumAdmin(admin.ModelAdmin):
    list_filter = [
        AutocompleteFilterFactory('Company', 'company', 'admin:custom_search', True)
    ]

    def get_urls(self):
        """As above..."""Customizing widget textYou can customize the text displayed in the filter widget, to use something
other thanstr(obj). This needs to be configured for both the dropdown
endpoint and the widget itself.In yourviews.py, overridedisplay_text:fromadmin_searchable_dropdown.viewsimportAutocompleteJsonViewclassCustomSearchView(AutocompleteJsonView):@staticmethoddefdisplay_text(obj):returnobj.my_str_method()defget_queryset(self):"""As above..."""Then use either of two options to customize the text.Option one is to specify the form_field in an AutocompleteFilter in youradmin.py:fromdjangoimportformsfromdjango.contribimportadminfromdjango.shortcutsimportreversefromadmin_searchable_dropdown.filtersimportAutocompleteFilterclassFuelChoiceField(forms.ModelChoiceField):deflabel_from_instance(self,obj):returnobj.my_str_method()classCarCompanyFilter(AutocompleteFilter):title='Company'field_name='company'form_field=FuelChoiceFielddefget_autocomplete_url(self,request,model_admin):returnreverse('admin:custom_search')classCarModelAdmin(admin.ModelAdmin):list_filter=[CarCompanyFilter]defget_urls(self):"""As above..."""Option two is to use an AutocompleteFilterFactory in youradmin.pyadd alabel_byargument:fromdjango.contribimportadminfromadmin_searchable_dropdown.filtersimportAutocompleteFilterFactoryclassCarModelAdmin(admin.ModelAdmin):list_filter=[AutocompleteFilterFactory('Company','company','admin:custom_search',True,label_by='my_str_method')]defget_urls(self):"""As above..."""Contributing:Based onthis StackOverflow question, and the comments that went unresolved in the selected answerandcode from FeinCMSandcode from mrts.To Contribute, please fork the project, make a pull-request, and clearly mention the problems or improvements your PR is addressing.License:Django Admin Searchable Dropdown is an Open Source project licensed under the terms of the MIT LICENSE.