ModelMultipleChoiceField save fails

I’ve been banging my head today trying to get a MultipleChoiceField or a ModelMultipleChoiceField to save correctly. I was finding that no matter which widgets I used, or which field types I was using, it was failing. I wouldn’t get any errors, and all the data would be saved except for my ManyToMany relationship.

So, after much ado creating custom widgets and scouring the web for advice, I found that I should have just read the ModelForm Documentation. There it was, under ‘The save() method”:

Another side effect of using commit=False is seen when your model has a many-to-many relation with another model. If your model has a many-to-many relation and you specify commit=False when you save a form, Django cannot immediately save the form data for the many-to-many relation. This is because it isn’t possible to save many-to-many data for an instance until the instance exists in the database.

I had been using save(commit=false) and hadn’t been using save_m2m(). That’ll teach me to read the documentation!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s