django filter multi select list in admin

Viewed 2276

I have a django model with a self referencing many to many field as below.

 class Product(ModelBase):
    name = models.CharField(max_length=1000)
    category = models.ForeignKey(Category, on_delete=models.DO_NOTHING)
    company = models.ForeignKey(Company, on_delete=models.DO_NOTHING)
    alternatives = models.ManyToManyField('self', symmetrical=False, blank=True)

I am not particularly happy with the django admin form which lists the options for alternatives as a multi-select list box, as with a large number of products it will become tedious to select an alternative product or products. enter image description here Is there a way I can enrich this user experience, I have looked at django-advanced-filters but it doesnt work with django 3. Essentially, if I could have a typeahead search to filter through the items in the list and also limit the initial list based on the category selected.

----UPDATED---- admin.py

@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
    search_fields = ['name', ]


@admin.register(Company)
class CompanyAdmin(admin.ModelAdmin):
    search_fields = ['name', ]
    list_display = ['name', 'website', ]


@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
    search_fields = ['name', ]
    list_filter = ['category', ]
    list_display = ['name', 'category', 'company', ]

Thanks for the help.

1 Answers

The default behavior of a ManyToManyField is to be displayed as a vertical display.

What you need to do is to add to your admin.py a line where it changes your ManyToManyField display to a horizontal one, using the filter_horizontal option.

from django.contrib import admin

@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
    search_fields = ['name', ]
    list_filter = ['category', ]
    list_display = ['name', 'category', 'company', ]
    filter_horizontal = ['alternatives', ]

It will then be displayed as the following on your admin page:

enter image description here

This example can be seen on your Authentication and Authorization admin on the Groups add form.

enter image description here

Related