Search code examples
djangodjango-admindjango-widget

How to use django admin many to many field selector widget


I want to use this Many to many field

How can I use it for my many to many modelform. Basically I want the add button, which allows me to add the many to many objects.


Solution

  • The implementation of that "add" button is actually admin-specific.

    In simple terms, you may use the wrapper located in django.contrib.admin.widgets.RelatedFieldWidgetWrapper. Consider what django.contrib.admin.options does:

    formfield.widget = widgets.RelatedFieldWidgetWrapper(
        formfield.widget, db_field.rel, self.admin_site,
        can_add_related=can_add_related)
    

    But that requires you to use admin-specific objects, such as admin_site, the admin javascript ans css files and urls. I would recommend you build your own "Add" interface, even if based on this wrapper.