我的代码:
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中的多个选择字段。预先感谢
答案 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方法以使其工作。