Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Forms save_m2m

Hi I have a model which has 2 many to many fields in it. one is a standard m2m field which does not use any through tables whereas the other is a bit more complecated and has a through table. I am using the Django forms.modelform to display and save the forms. The code I have to save the form is

if form.is_valid():
        f = form.save(commit=False)
        f.modified_by = request.user
        f.save()
        form.save_m2m()

When i try to save the form I get the following error:

Cannot set values on a ManyToManyField which specifies an intermediary model.

I know this is happening when I do the form.save_m2m() because of the through table. What I'd liek to do is tell Django to ignore the m2m field with the through table but still save the m2m field without the through table. I can then go on to manually save the data for the through table field.

Thanks

like image 660
John Avatar asked Dec 23 '09 14:12

John


1 Answers

If you have a model with multiple fields one is done with a through table and the other one is a regular many-to-many relation without a through table. You can still use save_m2m() to save the regular one. Simply add the through fields to your exclude list on your form.

Add inside your form class:

class Meta:
    model = YourModel
    exclude = ('m2mthroughfield',)
like image 64
Eric Avatar answered Oct 17 '22 17:10

Eric