Python Django:在表单中保存外键值会引发错误
我必须找到与外键相关的表 具有主要关键患者id(必需)和诊断具有外国关键患者的人口统计表。我创建了两种形式。我在第一个表单上保存字段,然后在诊断表单中自动完成患者字段 问题是,当我试图在诊断表单上保存字段的值时,我在第一个表单上得到一个错误,它说“此字段是必需的”,即使该字段的值在一分钟前就存储了 编辑:这是我的解决方案 input.html(模板) 型号.pyPython Django:在表单中保存外键值会引发错误,python,django,django-forms,django-views,Python,Django,Django Forms,Django Views,我必须找到与外键相关的表 具有主要关键患者id(必需)和诊断具有外国关键患者的人口统计表。我创建了两种形式。我在第一个表单上保存字段,然后在诊断表单中自动完成患者字段 问题是,当我试图在诊断表单上保存字段的值时,我在第一个表单上得到一个错误,它说“此字段是必需的”,即使该字段的值在一分钟前就存储了 编辑:这是我的解决方案 input.html(模板) 型号.py class demographic(models.Model): national_health_care_pat_id =
class demographic(models.Model):
national_health_care_pat_id = models.IntegerField('National Health Care patient id', null=True,blank=True)
patient_hospital_file_number = models.IntegerField(null=True,blank=True)
patient_id = models.IntegerField(unique= True ,primary_key=True)
def __str__(self):
return str(self.patient_id)
class diagnosis(models.Model):
patient = models.ForeignKey(demographic)
age_of_diagnosis = models.IntegerField(null=True,blank=True)
def __str__(self):
return str(self.patient_id)
class DemographicForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(DemographicForm, self).__init__(*args, **kwargs)
self.helper=FormHelper(self)
self.fields['date_of_birth'].widget = widgets.AdminDateWidget()
self.helper.layout = Layout(
'national_health_care_pat_id',
'patient_hospital_file_number',
'patient_id',
FormActions(
Submit('submit', "Save changes"),
Submit('cancel', "Cancel")
),
)
self.helper.form_tag = False
self.helper.form_show_labels = True
class Meta:
model = demographic
exclude = []
class DiagnosisForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(DiagnosisForm, self).__init__(*args, **kwargs)
self.helper=FormHelper(self)
self.helper.layout = Layout(
'patient',
'age_of_diagnosis',
FormActions(
Submit('submit', "Save changes"),
Submit('cancel',"Cancel")
),
)
self.helper.form_tag = False
self.helper.form_show_labels = True
class Meta:
model = diagnosis
exclude = []
forms.py
class demographic(models.Model):
national_health_care_pat_id = models.IntegerField('National Health Care patient id', null=True,blank=True)
patient_hospital_file_number = models.IntegerField(null=True,blank=True)
patient_id = models.IntegerField(unique= True ,primary_key=True)
def __str__(self):
return str(self.patient_id)
class diagnosis(models.Model):
patient = models.ForeignKey(demographic)
age_of_diagnosis = models.IntegerField(null=True,blank=True)
def __str__(self):
return str(self.patient_id)
class DemographicForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(DemographicForm, self).__init__(*args, **kwargs)
self.helper=FormHelper(self)
self.fields['date_of_birth'].widget = widgets.AdminDateWidget()
self.helper.layout = Layout(
'national_health_care_pat_id',
'patient_hospital_file_number',
'patient_id',
FormActions(
Submit('submit', "Save changes"),
Submit('cancel', "Cancel")
),
)
self.helper.form_tag = False
self.helper.form_show_labels = True
class Meta:
model = demographic
exclude = []
class DiagnosisForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(DiagnosisForm, self).__init__(*args, **kwargs)
self.helper=FormHelper(self)
self.helper.layout = Layout(
'patient',
'age_of_diagnosis',
FormActions(
Submit('submit', "Save changes"),
Submit('cancel',"Cancel")
),
)
self.helper.form_tag = False
self.helper.form_show_labels = True
class Meta:
model = diagnosis
exclude = []
你知道可能是什么问题吗?提前谢谢你 您需要传入实际的
人口统计对象,而不仅仅是诊断表单的ID
。Django希望ForeignKey
字段指向它们所表示的对象的实例。您还需要从诊断表单中排除患者
字段。这将阻止Django尝试验证该字段
# forms.py
class DiagnosisForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
. . .
class Meta:
model = diagnosis
exclude = ['patient']
# views.py
from django.shortcuts import get_object_or_404, render
from your_app.models import Patient
def input(request):
patient = get_object_or_404(Patient, id=5)
my_demographics = DemographicForm(request.POST or None)
my_diagnosis = DiagnosisForm(request.POST or None)
if request.method =='POST':
if my_demographics.is_valid() and my_diagnosis.is_valid():
demographic = my_demographics.save()
my_diagnosis.save(commit=False)
my_diagnosis.patient = demographic
my_diagnosis.save()
return render(request, 'input.html', {'frm':my_demographics, 'frm_d': my_diagnosis})
您可以将模型和表单类添加到代码示例中吗?@Brando当然可以!我添加了它们。您没有将数据传递到诊断表单
,只传递到人口统计表单
@Anentropic。您能更具体一点吗?我做错了什么?@zinon你真的应该用大写字母在Python中开始你的类名,以区分它们与实例变量。你能给我一个简单的例子吗?我已经为你添加了一个例子。我没有模型病人。患者只是诊断模型中的一个字段。我需要将患者编号添加到人口统计表中(在我按下此表的提交按钮后),并将其放入诊断表中,然后填写诊断表并保存。这就是我传递my_demographics_object.patient_id值的原因。my_Diagnostics=Diagnostisform(initial={'patient':'5'})
只是在得到正确的值之前给出一个初始值。因此,我填写了人口统计表,保存并从此表单获取“患者id”字段值,并将其作为诊断表单中“患者”字段的值。