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.
To be able to edit multiple objects from one Django admin, you need to use inlines. You can see the form to add and edit Villain inside the Category admin. If the Inline model has alot of fields, use StackedInline else use TabularInline .
First we install a package using pip: pip install django-nested-admin. Now we Add the library in settings.py: INSTALLED_APPS[ ... 'nested_admin', ... ]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With