Django: Search many to many field while creating object
Asked Answered
G

2

8

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?

Garlicky answered 11/7, 2018 at 6:54 Comment(0)
B
16

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',)
    ...
Butanol answered 11/7, 2018 at 7:2 Comment(0)
D
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)
Domitiladomonic answered 11/7, 2018 at 7:16 Comment(1)
Can BetterFilterWidget be used in a 'normal' form, out of the admin?Clash

© 2022 - 2024 — McMap. All rights reserved.