Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Search many to many field while creating object

I've got a use case where I have multiple Ingredient that can be linked to a Recipe through the Django admin. Now I have around a hundred ingredients which makes it very difficult to select the ingredients in the following UI.

enter image description here

Is there a way to add a search field or something similar to the django admin for easier selection?

like image 577
danialzahid94 Avatar asked Jul 11 '18 06:07

danialzahid94


1 Answers

You have few choices.

1. filter_horizontal

With filter_horizontal, you can use horizontal m2m ui in admin. I prefer this way using m2m in admin.

class YourAdmin(admin.ModelAdmin):
    filter_horizontal = ('m2m_field',)
    ...

And the result will be...

enter image description here

2. raw_id_fields docs

You can use raw_id_fields for using pop-up modal with your m2m fields.

It's bit useful when you have lots of m2m field. Also, it's easy to filter which m2m obj to add.

class YourAdmin(admin.ModelAdmin):
    raw_id_fiedls = ('m2m_field',)
    ...
like image 72
seuling Avatar answered Oct 14 '22 06:10

seuling