Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django autocomplete Light in list filters for admin

I have successfully setup the Autocomplete Registry and have my django admin forms where if you go to the form, the auto completes works. I would like to be able to extend the autocompletes to work on the list_filter view as well. So when you are looking at the view generated by Admin.py -- that the list_filter inputs that are generated would also use the autocomplete jquery + service URL.

I didn't see anything listed in the documentation, anyone have any pointers?

like image 679
Trent Brown Avatar asked Feb 14 '16 06:02

Trent Brown


1 Answers

If you are using Django version greater then 2.0, you can try using the built-in autocomplete fields for this purpose.

By default, the admin uses a select-box interface () for those fields. Sometimes you don’t want to incur the overhead of selecting all the related instances to display in the dropdown.

The Select2 input looks similar to the default input but comes with a search feature that loads the options asynchronously

There is a simple app which does this:

To install use: pip install django-admin-autocomplete-filter

Then add admin_auto_filters to your INSTALLED_APPS inside settings.py of your project.

Let's say we have following models:

class Artist(models.Model):
    name = models.CharField(max_length=128)

class Album(models.Model):
    name = models.CharField(max_length=64)
    artist = models.ForeignKey(Artist, on_delete=models.CASCADE)
    cover = models.CharField(max_length=256, null=True, default=None)

And you would like to filter results in Album Admin on the basis of artist, then you can define search fields in Artist and then define filter as:

from admin_auto_filters.filters import AutocompleteFilter

class ArtistFilter(AutocompleteFilter):
    title = 'Artist' # display title
    field_name = 'artist' # name of the foreign key field

class ArtistAdmin(admin.ModelAdmin):
    search_fields = ['name'] # this is required for django's autocomplete functionality
    ...

class AlbumAdmin(admin.ModelAdmin):
    list_filter = [ArtistFilter]
    
    '''
       defining this class is required for AutocompleteFilter
       it's a bug and I am working on it.
    '''
    class Media:
        pass

After following these steps you may see the filter as:

autocomplete filter

search as you type

like image 148
not2acoder Avatar answered Sep 19 '22 15:09

not2acoder