Using the UpdateView class on mtm with an intermediate model

How can I convince a general view based on the Django 1.3 class:

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

Do not give up so easily with an error:

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

Even if all fields of the intermediate model have default values, I cannot get a general general view of the class to save. The functional version also looks dirty. Django 1.3.

+1
source share
2 answers

You must extend UpdateViewand override the method form_valid()to manually save the intermediate model.

Personally, I never use generic representations directly from a URL pattern, I always extend them verbatim into views.py.

+1
source

As Berislav Lopak 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)

.

+1

All Articles