Autocomplete filters with django-grappelli

django-grappelli is simply much better admin. It looks nicer, has a few additional features, and doesn’t sacrifice anything form the original django admin.

Screen Shot 2014-03-22 at 22.26.36

One of it’s improvements is the way it renders filters on list view in admin – a select instead of the default links.

Screen Shot 2014-03-22 at 22.27.09

 

Another one is AJAX autocomplete widget for foreign key and many2many fields.

So, why not combine the two? Let’s make an autocomplete filter!

Django has opened admin list filter API to the world in version 1.4, so it’s no longer illegal to build custom filters. RIP django-admin-filtrate (although, it could be updated to work with new versions of Django, but that’s another topic.)

Making the autocomplete filter is simpler then it might look, but there are a few tricks to pull.

First, we need to enable AJAX view for the model we will filter by, if it is not already enabled. This step is also necessary when creating a regular foreign key or m2m autocomplete field, and is documented here. There are two ways to accomplish this (either by adding a method to Model or with a settings value), both will work just fine. I prefer the settings value approach:

GRAPPELLI_AUTOCOMPLETE_SEARCH_FIELDS = {
    "contacts": {
        "company": ("id__iexact", "name__icontains",),
        "targetgroup": ("id__iexact", "name__icontains",),
    },
}

The source code is available on GitHub:
https://github.com/frnhr/django-grappelli-filters