[Django]-Django: saving a ModelForm with custom many-to-many models

2👍

If you are using a custom M2M table using the through parameter, I believe you must do the saves manually in order to save the additional fields. So in your view you would add:

...
publication = form.save()
#assuming that these records are in order! They may not be
order_idx = 0
for author in request.POST.getlist('authors'): 
    authorship = Authorship(author=author, publication=publication, ordering=order_idx)
    authorship.save()
    order_idx += 1

You may also be able to place this in your ModelForm’s save function.

1👍

I’m not sure if there’s a hook for this, but you could save it manually with something like:

form = PublicationForm(...)
pub = form.save(commit=False)
pub.save()
form.save_m2m()

So you can handle any custom actions in between as required. See the examples in the docs for the save method.

👤ars

Leave a comment