本文介绍了在m-t-m上使用基于类的UpdateView与中介模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何说服基于Django 1.3类的通用视图:

  UpdateView.as_view(model = Category,
template_name ='generic_form.html',
success_url ='/ category /')

不要放弃这么容易的错误:

 无法在指定中间模型的ManyToManyField上设置值。 

即使中介模型中的所有字段都有默认值,我也无法获取基于类的通用视图保存。基于功能的版本看起来也很乱。 Django 1.3。

解决方案

正如Berislav Lopac所说:

 $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ 
$ $ b IntermediateModel.objects.filter(category = self.object).delete()
for form_lear_data中的other_side_model_object ['other_side_model_field']:
intermediate_model = IntermediateModel()
intermediate_model.category = self.object
intermediate_model.other_side_model_related_field = other_side_model_object
intermediate_model.save()
返回超级(ModelFormMixin,self).form_valid(form)
/ pre>

我回答了一些类似的。


How can I convince a Django 1.3 class based generic view:

UpdateView.as_view(model=Category,
template_name='generic_form.html',
success_url='/category/')

To not give up so easy with error:

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

Even if all fields in the intermediary model have defaults, I can't get the class based generic view to save. The functional based version looks messy also. Django 1.3.

解决方案

As Berislav Lopac says:

class CategoryView(UpdateView):
    model=Category
    def form_valid(self, form):
        self.object = form.save(commit=False)
        IntermediateModel.objects.filter(category = self.object).delete()
        for other_side_model_object in form.cleaned_data['other_side_model_field']:
            intermediate_model = IntermediateModel()
            intermediate_model.category = self.object
            intermediate_model.other_side_model_related_field= other_side_model_object
            intermediate_model.save()
        return super(ModelFormMixin, self).form_valid(form)

I answer some similar here.

这篇关于在m-t-m上使用基于类的UpdateView与中介模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 04:00