Django ManyToManyFields and Form.save(commit=false)

Tue May 5, 2009

Those django devs have done a whole lot of thinking, and we’re reaping all the benefits.

Let’s say you have a model with a ManyToManyField in it, but you can’t save the ModelForm outright because you have to set a user into it (or some other foreignkey field). So you do something like this:

item = form.save(commit=False)
item.user = request.User
item.save()

When you go to test your page, it looks like the ManyToManyFields are not getting saved – and that is because they are not. They are only saved when you save the form object, or manipulate the collections explicitly.

Look here: http://docs.djangoproject.com/en/1.0/topics/forms/modelforms/ and you’ll see there is a nifty function added to the form named save_m2m(). You have to call this explicitly when you save a form (with a ManyToManyField) with commit=False. So you should do this:

item = form.save(commit=False)
item.user = request.user
item.save()
form.save_m2m()