我试图在Django中使用UpdateView同时更新两个表单。我有get方法正常工作,但是当我提交更新时,post方法创建一个新的表单实例。如何从get方法中获取表单并更新它们而不创建新实例?一切都重定向,我没有错误。
class MotionStudyInstanceUpdateView(UpdateView):
model = MotionStudyInstance
fields = ['height', 'weight', 'skin_type_score', 'fitzpatrick_skin_type']
template_name = 'data/motionstudyinstance_update.html'
success_url = reverse_lazy('data:motion-studies')
def get_context_data(self, **kwargs):
pass
def get(self, request, **kwargs):
pk = self.kwargs['pk']
item = MotionStudyInstance.objects.get(id=pk)
general_info = item.general_info
form = MotionStudyInstanceForm(
initial={'height': item.height, 'weight': item.weight, 'skin_type_score': item.skin_type_score,
'fitzpatrick_skin_type': item.fitzpatrick_skin_type})
form_two = GeneralInfoForm(initial={'case_report_form_number': general_info.case_report_form_number,
'form_type': general_info.form_type,
'study_start_date': general_info.study_start_date,
'signed_consent': general_info.signed_consent,
'gender': general_info.gender,
'miscellaneous_notes': general_info.miscellaneous_notes,
'adverse_events': general_info.adverse_events})
return render(request, self.template_name, {'form': form, 'foreign_form': form_two})
def post(self, request, **kwargs):
if request.method == 'POST':
form = MotionStudyInstanceForm(request.POST)
foreign_form = GeneralInfoForm(request.POST)
if form.is_valid() and foreign_form.is_valid():
general_info = foreign_form.save()
user_form = form.save(commit=False)
user_form.general_info = general_info
user_form.save()
return redirect('data:motion-studies')
else:
form = MotionStudyInstanceForm()
return render(request, self.template_name, {'form': form})
forms.py
class MotionStudyInstanceForm(forms.ModelForm):
class Meta:
model = MotionStudyInstance
exclude = ('general_info',)
widgets = {
'validation_status': forms.HiddenInput(),
'author': forms.HiddenInput(),
'sibling': forms.HiddenInput()
}
class GeneralInfoForm(forms.ModelForm):
class Meta:
model = GeneralInfo
fields = '__all__'
widgets = {
'form_type': forms.HiddenInput(),
}
答案 0 :(得分:0)
看起来您应该在表单上使用instance参数。 所以你可以在帖子上更新它,并在get
上显示它类似的东西:
def post(self, request, **kwargs):
pk = self.kwargs['pk']
item = MotionStudyInstance.objects.get(id=pk)
if request.method == 'POST':
form = MotionStudyInstanceForm(request.POST, instance=item)