Django autocomplete Light in admin filter lists

I successfully set up an autocomplete registry and had my django admin forms, where if you go to the form, auto shuts down. I would like to be able to extend autocomplete to work on the list_filter view. Therefore, when you look at the view generated by Admin.py, that the inputs generated by list_filter will also use the jquery + autocomplete URL.

I have not seen anything in the documentation, who has pointers?

+5
source share
2 answers

You must define your own admin filter, which inherits from django.contrib.admin.SimpleListFilter . Then, a custom HTML template should be provided for this filter, which will use one of the django-autocomplete-light widgets. As a parameter for the widget, you must specify the required autocomplete URL. And don't forget to include the correct JS and CSS in it.

All this is done in a special application for this: dal-admin-filters

+1
source

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

By default, the administrator uses the select () interface for these fields. Sometimes you don’t want to take overhead when selecting all related instances to display in the drop-down list.

Input Select2 is similar to the default input, but comes with a search function that loads parameters asynchronously

There is a simple application that does this:

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

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

Say we have the 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 want to filter the results in Album Admin based on the artist, then you can define the search fields in Artist and then define the 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 autocomplete functionality ... class AlbumAdmin(admin.ModelAdmin): list_filter = [ArtistFilter] ''' defining this class is required for AutocompleteFilter it a bug and I am working on it. ''' class Media: pass 

After completing these steps, you can see the filter as:

autocomplete filter

search as you type

0
source

Source: https://habr.com/ru/post/1242972/


All Articles