Registry / web-framework / django-admin-autocomplete-filter

django-admin-autocomplete-filter

JSON →
library0.7.1pypypi✓ verified 86d ago

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.

pip install django-admin-autocomplete-filter
INSTALL
IMPORT
SIG · DJANGO-ADMIN-AUTOC
D
django-admin-autocomplete-filter
web-frameworkpythonv0.7.1
Install
3.4s avg
Import
926ms
Disk
66MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.7.1 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.920 runs
installs and imports cleanly · install 0.0s · import 0.987s · 66.4MB
glibc
py 3.103.920 runs
installs and imports cleanly · install 3.4s · import 0.865s · 67MB
66MB installed
● package 66MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

AutocompleteFilter
from admin_auto_filters.filters import AutocompleteFilter
AutocompleteFilterFactory
from admin_auto_filters.filters import AutocompleteFilterFactory

To use `django-admin-autocomplete-filter`, first add `admin_auto_filters` to your `INSTALLED_APPS`. Then, define `search_fields` on the `ModelAdmin` for the related model you wish to filter by. Finally, use `AutocompleteFilter` or `AutocompleteFilterFactory` in the `list_filter` of the `ModelAdmin` where you want the autocomplete filter to appear.

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
Debug
Known issues
breakingVersion 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.
fix
Upgrade to version 0.6.1 or higher (e.g., `pip install --upgrade django-admin-autocomplete-filter`).
affects: 0.6
gotchaFor 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.
fix
Ensure `search_fields` is properly defined in the `ModelAdmin` class of the related model (e.g., `search_fields = ['name']` in `ArtistAdmin`).
affects: All versions
gotchaWhen 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.
fix
If custom filtering is required, implement it within the related `ModelAdmin`'s `get_queryset` method, potentially with conditional logic to distinguish between standard requests and autocomplete requests.
affects: All versions (inherent to Django's autocomplete_fields interaction)
Errors
Common errors & fixes
Reverse for '<app_name>_<model_name>_autocomplete' not found.
This error occurs because the related ModelAdmin for the field being autocompleted (the target of the ForeignKey or ManyToManyField) does not have `search_fields` defined, which is essential for Django's built-in autocomplete functionality that `django-admin-autocomplete-filter` leverages.
fix
Add `search_fields` to the `ModelAdmin` of the related model. For example, if you have `AlbumAdmin` using an autocomplete filter for `Artist`, you must define `search_fields` in `ArtistAdmin`.

```python
# admin.py
from django.contrib import admin
from .models import Artist, Album
from admin_auto_filters.filters import AutocompleteFilter

class ArtistAdmin(admin.ModelAdmin):
    search_fields = ['name'] # <--- This is required

@admin.register(Album)
class AlbumAdmin(admin.ModelAdmin):
    list_filter = [
        ('artist', AutocompleteFilter), # Using a tuple form for direct application
        # Or, if using a custom filter class:
        # ArtistFilter
    ]

# Or register ArtistAdmin separately if it's not already registered
admin.site.register(Artist, ArtistAdmin)
```
The results could not be loaded.
This message typically appears in the browser's console or within the autocomplete widget itself, indicating a failure to fetch autocomplete suggestions. The most common cause is missing `search_fields` on the related ModelAdmin. It can also indicate other backend issues, such as a custom `get_queryset` returning unexpected data or authentication problems.
fix
First, ensure the `ModelAdmin` for the related model has `search_fields` defined. If the problem persists, check your browser's developer console for more detailed network errors or JavaScript issues. Also, verify that `admin_auto_filters` is added to your `INSTALLED_APPS` and that any custom `get_queryset` methods on the related `ModelAdmin` are correctly returning model instances.
AttributeError: 'str' object has no attribute 'pk'
This error arises when a function or template expects a Django model instance (which has a `pk` attribute representing its primary key) but receives a plain string or a dictionary instead. This often happens if an autocomplete view or a custom `get_queryset` method is configured to return just the values (e.g., `values_list` or `values`) of a field rather than actual model objects.
fix
Ensure that the `get_queryset` method in your `ModelAdmin` (or any custom view providing data for the autocomplete) always returns a queryset of *model instances*. Avoid using `.values()` or `.values_list()` if the consumer expects full model objects.

```python
# Example of incorrect (will cause error) vs. correct (fix) get_queryset
class MyRelatedModelAdmin(admin.ModelAdmin):
    search_fields = ['name']

    def get_search_results(self, request, queryset, search_term):
        queryset, use_distinct = super().get_search_results(request, queryset, search_term)
        # Incorrect: would return dictionaries, causing 'str' object has no attribute 'pk'
        # return queryset.filter(some_condition=True).values('id', 'name'), use_distinct

        # Correct: returns model instances
        return queryset.filter(some_condition=True), use_distinct
```
Uncaught TypeError: $(...).select2 is not a function
This JavaScript error indicates that the `select2` jQuery plugin, which Django's autocomplete fields rely on, is not loaded or initialized correctly. This can be due to static files not being served, conflicts with other JavaScript libraries, or issues with jQuery itself.
fix
Ensure that your static files are collected and served properly by running `python manage.py collectstatic` and configuring your web server to serve them. Verify that `admin_auto_filters` (or `autocompletefilter`) is correctly added to `INSTALLED_APPS` to ensure its static assets are included. If using custom templates or other frontend libraries, check for jQuery conflicts or ensure Select2 is loaded before it's called.
Upgrade
Version history
0.7.1latest on PyPI · released Sep 11, 2021
Audit
Dependencies
DjangorequiredThis is a Django admin application and requires Django version >= 2.0.
Agent activity
11 hits · last 30 days
node
10
Resources