Using class-based UpdateView on a m-t-m with an intermediary model

╄→尐↘猪︶ㄣ 提交于 2019-12-23 01:19:05

问题


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.


回答1:


You should extend UpdateView and override the form_valid() method to manually save the intermediary model.

Personally, I never use generic views directly from the URL pattern, I always extend them verbatim in views.py.




回答2:


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.



来源:https://stackoverflow.com/questions/11467287/using-class-based-updateview-on-a-m-t-m-with-an-intermediary-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!