我的代码: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 回答
红糖糍粑
TA贡献1815条经验 获得超6个赞
我认为您可以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
添加回答
举报
0/150
提交
取消