{"id":5902,"library":"django-admin-autocomplete-filter","title":"Django Admin Autocomplete Filter","description":"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.","status":"active","version":"0.7.1","language":"python","source_language":"en","source_url":"https://github.com/farhan0581/django-admin-autocomplete-filter","tags":["django","admin","autocomplete","filter","foreignkey","manytomany"],"install":[{"cmd":"pip install django-admin-autocomplete-filter","lang":"bash","label":"Install with pip"}],"dependencies":[{"reason":"This is a Django admin application and requires Django version >= 2.0.","package":"Django","optional":false}],"imports":[{"symbol":"AutocompleteFilter","correct":"from admin_auto_filters.filters import AutocompleteFilter"},{"symbol":"AutocompleteFilterFactory","correct":"from admin_auto_filters.filters import AutocompleteFilterFactory"}],"quickstart":{"code":"import os\nimport django\nfrom django.conf import settings\nfrom django.db import models\nfrom django.contrib import admin\n\nsettings.configure(\n    INSTALLED_APPS=[\n        'django.contrib.admin',\n        'django.contrib.auth',\n        'django.contrib.contenttypes',\n        'django.contrib.sessions',\n        'django.contrib.messages',\n        'django.contrib.staticfiles',\n        'admin_auto_filters', # Add this app\n        'my_app', # Your app name\n    ],\n    SECRET_KEY=os.environ.get('DJANGO_SECRET_KEY', 'a-very-secret-key-for-dev'),\n    TEMPLATES=[\n        {\n            'BACKEND': 'django.template.backends.django.DjangoTemplates',\n            'APP_DIRS': True,\n            'OPTIONS': {\n                'context_processors': [\n                    'django.template.context_processors.debug',\n                    'django.template.context_processors.request',\n                    'django.contrib.auth.context_processors.auth',\n                    'django.contrib.messages.context_processors.messages',\n                ],\n            },\n        },\n    ],\n    DATABASES={\n        'default': {\n            'ENGINE': 'django.db.backends.sqlite3',\n            'NAME': ':memory:',\n        }\n    },\n    STATIC_URL='/static/',\n    ROOT_URLCONF=__name__,\n    DEBUG=True\n)\ndjango.setup()\n\n# models.py example\nclass Artist(models.Model):\n    name = models.CharField(max_length=128)\n\n    def __str__(self):\n        return self.name\n\nclass Album(models.Model):\n    name = models.CharField(max_length=64)\n    artist = models.ForeignKey(Artist, on_delete=models.CASCADE)\n\n    def __str__(self):\n        return self.name\n\n# admin.py example\nfrom admin_auto_filters.filters import AutocompleteFilter\n\nclass ArtistFilter(AutocompleteFilter):\n    title = 'Artist' # display title\n    field_name = 'artist' # name of the foreign key field\n\n@admin.register(Artist)\nclass ArtistAdmin(admin.ModelAdmin):\n    search_fields = ['name'] # REQUIRED for Django's autocomplete functionality\n\n@admin.register(Album)\nclass AlbumAdmin(admin.ModelAdmin):\n    list_filter = [ArtistFilter]\n\n# Minimal URLConf for admin\nfrom django.urls import path\nfrom django.contrib import admin\n\nurlpatterns = [\n    path('admin/', admin.site.urls),\n]\n\n# To make it runnable for demonstration (normally run via manage.py runserver)\nif __name__ == '__main__':\n    print(\"Django Admin Autocomplete Filter setup example.\")\n    print(\"To see it in action, you'd typically run 'python manage.py runserver'\")\n    print(\"and navigate to the Django admin interface (e.g., /admin/album/)\")\n    print(\"You'll need to create a superuser and some Artist/Album objects.\")\n\n    # Example of how you would apply migrations and create a superuser\n    # from django.core.management import call_command\n    # call_command('makemigrations', 'my_app')\n    # call_command('migrate')\n    # call_command('createsuperuser') # follow prompts\n\n","lang":"python","description":"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."},"warnings":[{"fix":"Upgrade to version 0.6.1 or higher (e.g., `pip install --upgrade django-admin-autocomplete-filter`).","message":"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.","severity":"breaking","affected_versions":"0.6"},{"fix":"Ensure `search_fields` is properly defined in the `ModelAdmin` class of the related model (e.g., `search_fields = ['name']` in `ArtistAdmin`).","message":"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.","severity":"gotcha","affected_versions":"All versions"},{"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.","message":"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.","severity":"gotcha","affected_versions":"All versions (inherent to Django's autocomplete_fields interaction)"}],"env_vars":null,"search_vec":"'0.7.1':61 'activ':42 'admin':2,15,63 'app':8 'autocomplet':3,18,27,64 'bug':48 'built':25 'built-in':24 'current':58 'django':1,7,14,22,62 'featur':55 'field':28 'filter':4,12,65 'fix':49 'foreign':31 'foreignkey':66 'function':29 'improv':57 'key':32 'leverag':21 'librari':40 'list':11 'maintain':43 'major':51 'mani':35,37 'many-to-mani':34 'manytomani':67 'minor':45 'new':54 'relationship':38 'releas':46,52 'render':10 'simpl':6 'use':16 'version':59 'widget':19","created_at":"2026-04-14T18:33:24.298390+00:00","updated_at":"2026-04-16T14:27:09.665800+00:00","problems":[{"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`.\n\n```python\n# admin.py\nfrom django.contrib import admin\nfrom .models import Artist, Album\nfrom admin_auto_filters.filters import AutocompleteFilter\n\nclass ArtistAdmin(admin.ModelAdmin):\n    search_fields = ['name'] # <--- This is required\n\n@admin.register(Album)\nclass AlbumAdmin(admin.ModelAdmin):\n    list_filter = [\n        ('artist', AutocompleteFilter), # Using a tuple form for direct application\n        # Or, if using a custom filter class:\n        # ArtistFilter\n    ]\n\n# Or register ArtistAdmin separately if it's not already registered\nadmin.site.register(Artist, ArtistAdmin)\n```","cause":"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.","error":"Reverse for '<app_name>_<model_name>_autocomplete' not found."},{"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.","cause":"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.","error":"The results could not be loaded."},{"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.\n\n```python\n# Example of incorrect (will cause error) vs. correct (fix) get_queryset\nclass MyRelatedModelAdmin(admin.ModelAdmin):\n    search_fields = ['name']\n\n    def get_search_results(self, request, queryset, search_term):\n        queryset, use_distinct = super().get_search_results(request, queryset, search_term)\n        # Incorrect: would return dictionaries, causing 'str' object has no attribute 'pk'\n        # return queryset.filter(some_condition=True).values('id', 'name'), use_distinct\n\n        # Correct: returns model instances\n        return queryset.filter(some_condition=True), use_distinct\n```","cause":"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.","error":"AttributeError: 'str' object has no attribute 'pk'"},{"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.","cause":"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.","error":"Uncaught TypeError: $(...).select2 is not a function"}],"ecosystem":"pypi","meta_description":null,"install_score":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":"0.7.1","cli_name":"","cli_version":null,"type":"library","homepage":null,"github":"https://github.com/farhan0581/django-admin-autocomplete-filter","docs":null,"changelog":null,"pypi":"https://pypi.org/project/django-admin-autocomplete-filter/","npm":null,"openapi_spec":null,"status_page":null,"smithery":null,"categories":["web-framework","database"],"base_url":null,"auth_type":null,"provenance":{"verified_status":"passing","verified_at":"2026-06-28","last_verified":"2026-06-28","next_check":"2026-07-28","install_tag":null}}