django-我的表单不会保存添加的M2M对象。为什么?

时间:2019-01-16 03:23:51

标签: python django

我的代码:

class DataSourceCreateView(CreateView):
    model = DataSource
    form_class = DataSourceForm
    template_name = 'engine/datasource_create.html'

    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        kwargs['user'] = self.request.user
        return kwargs

    def form_valid(self, form):

        f = form.save(commit=False)
        f.creator = self.request.user

        f.save()
        dsr_pk = form.cleaned_data['dataset_request']
        if dsr_pk != 'noval':
            print(dsr_pk)
            dsr = DatasetRequest.objects.get(pk=dsr_pk)
            f.dataset_requests.add(dsr)
            print(f)
            print(f.dataset_requests)
            f.save()

        return super(DataSourceCreateView, self).form_valid(form)

为什么我的表单未将dsr添加到f.dataset_requests?该表单可以保存并继续运行,而无需向dsr添加f.dataset_requests。我将dataset_request字段设置为单个选择字段,而不是DataSourceForm中的多个选择字段。预先感谢

2 个答案:

答案 0 :(得分:0)

我认为您可以使用save_m2m保存ManyToMany关系。您可以尝试这样:

class DataSourceCreateView(CreateView):
    model = DataSource
    form_class = DataSourceForm
    template_name = 'engine/datasource_create.html'

    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        kwargs['user'] = self.request.user
        return kwargs

    def form_valid(self, form):

        f = form.save(commit=False)
        f.creator = self.request.user
        f.save()
        form.save_m2m()
        return HttpResponseRedirect(self.get_success_url())  # Not calling Super here

答案 1 :(得分:0)

最终覆盖了我的DataSourceForm的save方法以使其工作。