Python – Adding inline many to many objects in Django admin

djangodjango-admindjango-formspython

I'm fairly new to Django and having read the documentation on its relational models and inline admin forms (docs on InlineModelAdmin) I'm struggling to figure out if the following is possible out of the box, or if I should roll my own forms.

Let's say I have two objects: Films and Directors, this is a many-to-many relationship as defined in in the model declarations as follows:

class Film(Model):
    director = ManyToManyField('Director')

Now in the detail form for a Film object I would like to add inline Director objects (they just have a name field as sole property). Not just selecting existing instances, but being able to create new ones, inline in the form of the Film object.

class DirectorInline(admin.TabularInline):
    model = Director
    extra = 3


class FilmAdmin(admin.ModelAdmin):
    inlines = (
        DirectorInline,
        )

This throws an error, because it expects a foreign key on the Director object.
Is what I'm trying to achieve possible without creating a custom form, validator etc. ?
Any tips in the right direction would be greatly appreciated, thanks in advance.

Best Answer

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.

Related Topic