开发者

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 for开发者_如何学JAVAms. 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


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',)


you can't save the m2m "without the through table"

the data you want to save is stored in the through table (and only in the through table)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜