Skip to main content

django-admin-select-filter

Build status on Github Current version on PyPi PyPI - Python Version PyPI - Django Version Downloads

Select2-powered admin list filters for Django.

Select2 filters in the admin sidebar

Install

pip install django-admin-select-filter

Add to INSTALLED_APPS:

INSTALLED_APPS = [
    ...
    "django_admin_select_filter",
]

Usage

ChoiceFilter

The main filter: it works on any field with discrete values — a choices-backed CharField/IntegerField, a BooleanField, or an explicit options list you provide yourself:

from django.contrib import admin
from django_admin_select_filter import ChoiceFilter

from myapp.models import Book


class GenreFilter(ChoiceFilter):
    parameter_name = "genre"  # reads Book.genre.choices


class StatusFilter(ChoiceFilter):
    parameter_name = "status"
    options = [("draft", "Draft"), ("published", "Published")]


@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
    list_filter = [GenreFilter, StatusFilter]

ChoiceFilter dropdown open, listing Fiction/Non-fiction

Since options accepts any explicit (value, label) list, ChoiceFilter can even filter a ForeignKey — pass one pair per related row:

class AuthorChoiceFilter(ChoiceFilter):
    parameter_name = "author"
    options = [(author.pk, str(author)) for author in Author.objects.all()]

This isn't optimal, though: options is evaluated once, when the class body runs (at import time), so it goes stale as rows are added or renamed — there's no live query, search, or async loading behind it. For a real ForeignKey, use ForeignKeyFilter below instead.

ForeignKeyFilter

Built specifically for ForeignKey/ManyToManyFields: it queries the related model live, supports searching through the related model's own ModelAdmin.search_fields, and can defer loading options until the widget is opened (see async_call further down).

from django_admin_select_filter import ForeignKeyFilter


class AuthorFilter(ForeignKeyFilter):
    parameter_name = "author"
    ordering = ["name"]


@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
    list_filter = [AuthorFilter]

ForeignKeyFilter dropdown with a search box, listing authors

model is only needed when it can't be inferred. By default it's resolved by walking parameter_name across Book's relations, following a nested lookup (e.g. parameter_name = "author__country") segment by segment — forward or reverse — and taking the last segment's related model. Set model explicitly if the lookup isn't a real relation chain, or to point somewhere else.

field_list_filter()

For a one-off filter that doesn't need its own subclass, use Django's own list_filter shorthand — a (field_name, filter_class) tuple — via field_list_filter():

from django_admin_select_filter import ChoiceFilter, ForeignKeyFilter, field_list_filter


@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
    list_filter = [
        ("author", field_list_filter(ForeignKeyFilter)),
        ("genre", field_list_filter(ChoiceFilter)),
    ]

parameter_name (and, for ForeignKeyFilter, model) is inferred from the field automatically — including a nested lookup like "author__country" — so the same wrapped class can be reused across as many fields as you like. It only supports async_call = False; for an async_call filter, define a dedicated subclass instead (field_list_filter() raises TypeError right away if you pass it one, rather than fail silently later).

Pass parameter_name to give it its own name in the URL, while it keeps filtering by the field: ("author__country", field_list_filter(ForeignKeyFilter, parameter_name="country")) reads ?country=3.

Shared options

Both filters share the same options: filter_only_used_values, async_call, searchable, nullable, null_label and title (by default, as Django's own filters, the field's verbose name). Both also support a nested lookup for parameter_name (e.g. "author__status"), resolving the field — and, for ForeignKeyFilter, the model — by walking each __-separated relation in turn, forward or reverse.

parameter_name is what the query string shows (?author=3), and by default also the lookup the filter applies. Set field_name when they differ — a shorter or translated name in the URL, or two filters on the same field:

class CountryFilter(ForeignKeyFilter):
    parameter_name = _("country")  # ?country=3, or ?país=3 in Spanish
    field_name = "author__country"  # what it filters by

Everything that touches the database (the lookup, the used values, the empty-value option, model and the choices' inference, the async counts) reads field_name; the URL and the async endpoint read parameter_name. A translated parameter_name follows the request's language, except with the async endpoint's use_registry, which keeps the one it was built in.

theme sets the Select2 theme; by default Select2's own, styled like the admin (or admin-autocomplete with django-unfold).

The empty-value option (when the field is nullable) reads like the rest of the admin: by default the ModelAdmin's empty_value_display ("-" unless changed). Set null_label to name it, or override get_null_label(request) to choose it per request:

class AuthorFilter(ForeignKeyFilter):
    parameter_name = "author"
    null_label = _("No author")

Set searchable = False to hide the search input entirely and get a plain dropdown instead — best for a short, static option list.

Set multiple = True to let either filter accept several values at once:

class AuthorFilter(ForeignKeyFilter):
    parameter_name = "author"
    multiple = True

multiple = True with two selected author chips

Selected values are joined in the query string with multiple_separator ("," by default) and applied with an __in lookup, so configured values (primary keys, option values) must not contain that character. The "All" option is dropped in this mode — clearing every selected chip already means no filter.

More of each option

get_option_data(value, label, obj=None) gives each option anything more JSON can carry — the package doesn't read it, the page does (obj: a ForeignKeyFilter's object):

class ProfessionalFilter(ForeignKeyFilter):
    parameter_name = "professional"
    option_template = "agenda/professional_option.html"  # optional

    def get_option_data(self, value, label, obj=None):
        return {"specialty": obj.specialty, "pending": obj.pending_count}
  • option_template renders each option (value, label, obj, data and filter in its context), shown as it renders in the list and as the selection, without any JavaScript; the search still matches its label. Escaped as any template, it's the server's HTML.
  • On the page, each option has them: an <option>'s data-option ({"data": …, "html": …}), an async result's data and html (not with admin_autocomplete, whose endpoint is the admin's). djangoAdminSelectFilter.optionOf(item) reads them from either (a Select2 item), for your own rendering:
djangoAdminSelectFilter.register({
    appliesTo: (select) => select.dataset.parameterName === "professional",
    extendOptions: (select, options) => {
        // Any of Select2's options.
        options.templateResult = (item) =>
            `${item.text} (${djangoAdminSelectFilter.optionOf(item).data.pending ?? 0})`;
    },
});

A script of yours that runs before the filters' (an admin's Media) may also push onto window.djangoAdminSelectFilterPlugins, an array.

  • With multiple = True, each selected value's chip is its selection too: option_template shows in it, and Select2's templateSelection(item, container) has the chip itself (container) for its own look — in the option's color, say — both when chosen and after the page reloads with it:
options.templateSelection = (item, container) => {
    const { data } = djangoAdminSelectFilter.optionOf(item);
    if (data.color) container.css("background-color", data.color);
    return item.text;
};

Each feature, a mixin

BaseSelectFilter (and so both filters) is the sum of one mixin per feature, in django_admin_select_filter.mixins: each one has its options, its part of the filtering and the script it needs, added to media only when it's on.

Mixin Options
UsedValuesMixin filter_only_used_values
NullOptionMixin nullable, null_label
MultipleValuesMixin multiple, multiple_separator
SearchableMixin searchable
AsyncOptionsMixin async_call, async_call_url

The options are set on the filter as always (multiple = True): the mixins are where to look for, or override, what each one does.

Async options (async_call = True)

Set async_call = True on a filter to defer loading its options until the Select2 widget is opened, fetching them over AJAX instead of rendering every option upfront — useful for a related model with many rows. It requires wiring an options endpoint: drop django_admin_select_filter_path() into your root urlpatterns — no include() needed:

# urls.py
from django_admin_select_filter import django_admin_select_filter_path

urlpatterns = [
    ...
    django_admin_select_filter_path(),
]

Its route defaults to django_admin_select_filter/options/; pass route in case it collides with something else in your project:

django_admin_select_filter_path(route="custom-options/")

The endpoint stays reversible as admin_select_filter:options either way — django_admin_select_filter_path() still namespaces it internally via include(), that's just no longer something you have to write yourself. Pass route, view, name or as_view_kwargs to customize it further. If you pass a custom name, set async_call_url explicitly on every async_call filter to match it — filters resolve the default endpoint by its default name, and have no way to discover a custom one chosen here.

Each async_call filter reads that shared endpoint through BaseSelectFilter.async_call_url, resolved automatically at request time via reverse("admin_select_filter:options"). Set async_call_url on a specific filter to point it at a different view instead:

class AuthorFilter(ForeignKeyFilter):
    parameter_name = "author"
    async_call = True
    async_call_url = "/api/custom-author-options/"

If its route shares a prefix with your admin mount (e.g. both under admin/), list django_admin_select_filter_path() before path("admin/", admin.site.urls). Since Django 4.1, AdminSite registers a catch-all view (AdminSite.final_catch_all_view, enabled by default) that matches every otherwise-unmatched URL under its own prefix and raises Http404 itself — so if the admin mount comes first, it swallows requests to this app's options endpoint before its URLs ever get a chance to match, and you'll see a 404 with a full HTML body (the admin's own "Page not found" page) instead of this app's JSON response.

The filter template loads jQuery/Select2 from Django admin's bundled vendor assets on demand, so no extra JS dependency is required. Make sure django.contrib.staticfiles is installed and configured.

The endpoint only serves filters with async_call = True and requires the requesting user to have view permission on the target model (checked via ModelAdmin.has_view_permission) — anonymous or unprivileged requests get a 403, and a parameter_name matching a non-async filter gets a 404. It looks the model up across every registered AdminSite (not just the default django.contrib.admin.site), so a project using its own AdminSite works too.

By default it does this by calling get_list_filter() on every matching ModelAdmin on every request. For a project with many admins or filters, pass as_view_kwargs={"use_registry": True} to django_admin_select_filter_path() instead: it resolves filters from a {site: {app_label: {model_name: {parameter_name: filter}}}} map built once and cached for the process's lifetime (admin registrations are static after startup), turning that per-request scan into a single dict lookup. The trade-off: it calls get_list_filter(request=None) while building the cache, so a get_list_filter() override that depends on the request isn't supported in this mode.

With the admin's autocomplete (admin_autocomplete = True)

A ForeignKeyFilter can load its options from the admin's own autocomplete endpoint instead — the one autocomplete_fields uses, already routed by admin.site.urls — so there's no django_admin_select_filter_path() to add:

class AuthorFilter(ForeignKeyFilter):
    parameter_name = "author"
    admin_autocomplete = True  # implies async_call

The related model needs a ModelAdmin with search_fields on the site: the search is that admin's, with its permissions and the foreign key's limit_choices_to, paginated as you scroll. "All" and the empty option (when the field is nullable) are added by the filter. Compared with the package's own endpoint, it searches every related object (filter_only_used_values doesn't apply), has no facet counts, and only works on relations (parameter_name ending in a ForeignKey or a ManyToManyField, nested lookups too): ChoiceFilter keeps using async_call.

Themes

Translations

Ships a Spanish (es) translation; its texts otherwise come from Django's own catalogs, so they follow the admin's language. Select2's own messages ("No results found", "Searching…") load the same translation file the admin's autocomplete fields use for the active language.

Contributing

See CONTRIBUTING.md for development setup, running the test suite (including the browser-driven e2e tests), and pre-commit hooks.

Metadata

Release files for django-admin-select-filter 0.1.7

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for django-admin-select-filter 0.1.7
File Size Uploaded Provenance Actions
django_admin_select_filter-0.1.7.tar.gz 485.4 kB With provenance Details for django_admin_select_filter-0.1.7.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for django-admin-select-filter 0.1.7
File Interpreter ABI Platform Actions
django_admin_select_filter-0.1.7-py3-none-any.whl Python 3 none any Details for django_admin_select_filter-0.1.7-py3-none-any.whl

Total release size: 519.9 kB

Release files / django_admin_select_filter-0.1.7.tar.gz

Download URL django_admin_select_filter-0.1.7.tar.gz
Size 485.4 kB
Tags Source
SHA-256 checksum
How to use checksums
58f6df84b3908a929af458d8b7157178fb17a465ca764f671dd46e70338d35b6
BLAKE2b-256 checksum
How to use checksums
e7be0a815f369fad8c9b6b74bad9173d0b7a1d269d9ff025fde095e55b5dca26
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 29, 2026.

Transparency log

Release files / django_admin_select_filter-0.1.7-py3-none-any.whl

Download URL django_admin_select_filter-0.1.7-py3-none-any.whl
Size 34.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
6d963795d2dcbbbde2667b8708835371932f4578c94e1f60e84b43548d6a8614
BLAKE2b-256 checksum
How to use checksums
757ceacdad486434f9d57ba8875a29ea2b84988a5d6394bbd43f6eee527f0d9a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 29, 2026.

Transparency log

Security for django-admin-select-filter 0.1.7

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for django_admin_select_filter-0.1.7.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 29, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page