我很难处理特殊情况。我使用UpdateView
来提供标准表单(具体为ModelForm
)和内嵌表单集。
views.py
代码如下所示:
class Contract(LoginRequiredMixin, UpdateView):
template_name = '/path/to/template.html'
model = ContractModel
form_class = ContractModelForm
success_url = reverse_lazy('contract-list')
def get_context_data(self, **kwargs):
context = super(ContractVerificationUpdate, self).get_context_data(**kwargs)
if self.request.POST:
context['student_form'] = StudentsFormSet(self.request.POST)
else:
context['student_form'] = StudentsFormSet(instance=self.object)
return context
def form_valid(self, form):
self.object = form.save(commit=False)
context = self.get_context_data()
student_form = context['student_form']
if student_form.is_valid():
self.object = form.save()
student_form.instance = self.object
student_form.save()
return HttpResponseRedirect(self.get_success_url())
else:
return self.render_to_response(self.get_context_data(form=form))
当我打开这个更新视图时,在这个合同模型上分配的学生都按预期显示,但是当我编辑它们时(例如我编辑学生的名字),然后我点击了保存按钮,它没有得救了。使用我的调试器,我已经确认它到达了行student_form.save()
,它应该更新我想要的对象,尽管它不会自行保存。这有什么问题?
它可能很容易解决,但我的思绪真的被困在这一点上!非常欢迎任何形式的帮助或建议!
提前谢谢!
答案 0 :(得分:1)
您需要在保存之前致电form.is_valid()
。
像这样编辑您的视图,
def form_valid(self, form):
self.object = form.save(commit=False)
context = self.get_context_data()
student_form = context['student_form']
if form.is_valid() and student_form.is_valid():
self.object = form.save()
student_form.instance = self.object
student_form.save()
return HttpResponseRedirect(self.get_success_url())
else:
return self.render_to_response(self.get_context_data(form=form))