[Django]-Adding inline many to many objects in Django admin

42πŸ‘

βœ…

The default widget for Many-to-many field in admin or widgets with filter_vertical or filter_horizontal property allows you to add new item. There is a green β€œ+” sign near the field to open a popup window and add new Director instance.

But if you need the inline style admin you should reference to the through-model. If you don’t specify the custom model Django creates a simple model with 2 foreign keys to Director and Film.

So you can try to create inline like

class DirectorInline(admin.TabularInline):
    model = Film.director.through
    extra = 3

This will not raise an exception and will generate an inline form, but you will have to select directors from drop-down list. I think you can overwrite this by using custom form.

πŸ‘€Igor

6πŸ‘

The simplest way to add a β€œ+” button next to a ManyToManyField is to make sure that both objects are registered in your admin.py file. Otherwise Django won’t create a form for the second type of object

admin.py

admin.site.register(Film)
admin.site.register(Director)
πŸ‘€Justin

Leave a comment