Home > Back-end >  How to add a search field for Django Admin Change/Add forms?
How to add a search field for Django Admin Change/Add forms?

Time:05-23

CONTEXT

I am making a birthday app where the Admin can input their friends birthdays and gifts they wish to buy for them. The gifts are in a separate table and the friends_birthday table refers to this gifts table by a manytomanyfield. When creating a piece of data for their friend (i.e. firstname, birthday, etc.) the Admin must first create a gift for them via the gift table, then create a row in the 'friends_user' table that adds their info and gift(s).

Problem

When the Admin is adding the gifts to their friends, the default setting is a box populated by many gifts, some of which they are assigning to their other friends. However, if the project scales, then the box would overflow and simply highlighting the choices would not work. Hence, I want to create a search bar in the add/change form in Django Admin.

enter image description here

Any ideas? Thanks in advance.

CodePudding user response:

You can use filter_horizontal to get better widget with filter/search option built in

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

It looks something like this:

Screenshot

CodePudding user response:

Try adding autocomplete_fields in your admin.py https://docs.djangoproject.com/en/4.0/ref/contrib/admin/#django.contrib.admin.ModelAdmin.autocomplete_fields

  • Related