Django Admin Autocomplete Filter
A simple Django app to render list filters in django admin using an autocomplete widget. It leverages Django's built-in `autocomplete_fields` functionality for foreign key and many-to-many relationships. The library is actively maintained, with minor releases for bug fixes and major releases for new features and improvements. Current version is 0.7.1.
Warnings
- breaking Version 0.6 introduced a bug in its JavaScript files, requiring an immediate patch in version 0.6.1. Users upgrading to 0.6 should ensure they update to 0.6.1 or later to avoid front-end issues.
- gotcha For the autocomplete filter to function correctly, the `ModelAdmin` of the *related model* (the one being filtered by, e.g., `ArtistAdmin` when filtering `Album` by `Artist`) MUST have `search_fields` defined. Without this, you will encounter 'Reverse for '<app_name>_<model_name>_autocomplete' not found' errors or autocomplete results will fail to load.
- gotcha When a field is configured as an autocomplete field in Django Admin, the `get_queryset` method of the related model's `ModelAdmin` is directly called to fetch results. This can bypass and effectively override `ModelForm` filtering logic defined in `__init__` or `clean` methods, leading to unexpected filter behavior or invalid choices appearing in the autocomplete dropdown.
Install
-
pip install django-admin-autocomplete-filter
Imports
- AutocompleteFilter
from admin_auto_filters.filters import AutocompleteFilter
- AutocompleteFilterFactory
from admin_auto_filters.filters import AutocompleteFilterFactory
Quickstart
import os
import django
from django.conf import settings
from django.db import models
from django.contrib import admin
settings.configure(
INSTALLED_APPS=[
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'admin_auto_filters', # Add this app
'my_app', # Your app name
],
SECRET_KEY=os.environ.get('DJANGO_SECRET_KEY', 'a-very-secret-key-for-dev'),
TEMPLATES=[
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
],
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
},
STATIC_URL='/static/',
ROOT_URLCONF=__name__,
DEBUG=True
)
django.setup()
# models.py example
class Artist(models.Model):
name = models.CharField(max_length=128)
def __str__(self):
return self.name
class Album(models.Model):
name = models.CharField(max_length=64)
artist = models.ForeignKey(Artist, on_delete=models.CASCADE)
def __str__(self):
return self.name
# admin.py example
from admin_auto_filters.filters import AutocompleteFilter
class ArtistFilter(AutocompleteFilter):
title = 'Artist' # display title
field_name = 'artist' # name of the foreign key field
@admin.register(Artist)
class ArtistAdmin(admin.ModelAdmin):
search_fields = ['name'] # REQUIRED for Django's autocomplete functionality
@admin.register(Album)
class AlbumAdmin(admin.ModelAdmin):
list_filter = [ArtistFilter]
# Minimal URLConf for admin
from django.urls import path
from django.contrib import admin
urlpatterns = [
path('admin/', admin.site.urls),
]
# To make it runnable for demonstration (normally run via manage.py runserver)
if __name__ == '__main__':
print("Django Admin Autocomplete Filter setup example.")
print("To see it in action, you'd typically run 'python manage.py runserver'")
print("and navigate to the Django admin interface (e.g., /admin/album/)")
print("You'll need to create a superuser and some Artist/Album objects.")
# Example of how you would apply migrations and create a superuser
# from django.core.management import call_command
# call_command('makemigrations', 'my_app')
# call_command('migrate')
# call_command('createsuperuser') # follow prompts