Autocomplete List Filter in Django Admin

Farhan Khan
Cashify Engineering
3 min readNov 23, 2018

With the coming of Django version 2.0, we have now got an autocomplete functionality in the admin panel. As stated in the docs:

autocomplete_fields is a list of ForeignKey and/or ManyToManyField fields you would like to change to Select2 autocomplete inputs.

By default, the admin uses a select-box interface (<select>) for those fields. Sometimes you don’t want to incur the overhead of selecting all the related instances to display in the drop-down.

The Select2 input looks similar to the default input but comes with a search feature that loads the options asynchronously. This is faster and more user-friendly if the related model has many instances.

Now we can use the autocomplete functionality in the Django admin’s ‘Change’ or ‘Add Page’. However, for the list filters, we still have the old way of displaying the items, as listed below:

Default Admin List Filter

Now consider the scenario when you have a large number of records. The list grows to such an extent that it becomes cumbersome and difficult to use.

So to solve this, there is a simple app which uses Django’s autocomplete widget to render the list filter.

Install it via pip as: pip install django-admin-autocomplete-filter

Then add admin_auto_filters to your INSTALLED_APPS inside settings.py of your project.

Usage:

Let’s say we have the following models:

class Artist(models.Model):
name = models.CharField(max_length=128)
class Album(models.Model):
name = models.CharField(max_length=64)
artist = models.ForeignKey(Artist, on_delete=models.CASCADE)
cover = models.CharField(max_length=256, null=True, default=None)

Moreover, you would like to filter results in Album Admin by the ‘artist’; then you can define search fields in Artist and define filter as:

from admin_auto_filters.filters import AutocompleteFilterclass ArtistFilter(AutocompleteFilter):
title = 'Artist' # display title
field_name = 'artist' # name of the foreign key field
class ArtistAdmin(admin.ModelAdmin):
search_fields = ['name'] # this is required for django's autocomplete functionality
...
class AlbumAdmin(admin.ModelAdmin):
list_filter = [ArtistFilter]
...

After following these steps, you may see the filter in Album Admin page as:

Using Autocomplete Widget
Search As You Type

The autocomplete functionality uses the get_search_results method to get the results. So to modify the search results you may consider overriding this method in the concerned admin class.

Similarly, the pagination is controlled by model admin’s get_paginator method. You may override these and provide your custom view using the autocomplete_view method in your admin class.

--

--