7

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?

danialzahid94
  • 4,103
  • 2
  • 19
  • 31

2 Answers2

13

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',)
    ...
5parkp1ug
  • 462
  • 6
  • 17
seuling
  • 2,850
  • 1
  • 13
  • 22
1

I suppose you want to filter over ingredients and select it one by one on admin UI

You can use django forms builtin CheckboxSelectMultiple widget in place of SelectMultiple to make selection easy

from django import forms
from django.contrib import admin

class RecipeForm(forms.ModelForm):

    class Meta(object):
        model = Recipe
        widgets = {
            'Ingredient': forms.CheckboxSelectMultiple,
        }


class RecipeAdmin(admin.ModelAdmin):

    form = RecipeForm

admin.site.register(Recipe, RecipeAdmin)

Alternatively, you can use django-better-filter-widget package if you want a search input on choices, Refer Github repo for installation

It is a custom widget, created by overriding SelectMultiple widget of django forms

from django import forms
from django.contrib import admin
from better_filter_widget import BetterFilterWidget

class RecipeForm(forms.ModelForm):

    class Meta(object):
        model = Recipe
        widgets = {
            'Ingredient': BetterFilterWidget(),
        }


class RecipeAdmin(admin.ModelAdmin):
    form = RecipeForm

admin.site.register(Recipe, RecipeAdmin)
Satendra
  • 6,755
  • 4
  • 26
  • 46