【发布时间】:2017-03-09 19:43:06
【问题描述】:
我想为以下表单创建错误消息:
class ExaminationCreateForm(forms.ModelForm):
class Meta:
model = Examination
fields = ['patient', 'number_of_examination', 'date_of_examination']
型号:
class Patient(models.Model):
patientID = models.CharField(max_length=200, unique=True, help_text='Insert PatientID')
birth_date = models.DateField(auto_now=False, auto_now_add=False, help_text='YYYY-MM-DD')
gender = models.CharField(max_length=200,choices=Gender_Choice, default='UNDEFINED')
class Examination(models.Model):
number_of_examination = models.IntegerField(choices=EXA_Choices)
patient = models.ForeignKey(Patient, on_delete=models.CASCADE)
date_of_examination = models.DateField(auto_now=False, auto_now_add=False, help_text='YYYY-MM-DD')
每位患者有 2 次检查(检查次数 = 选择 1 或 2),并且当第二次检查的日期
解决方案:`
def clean_date_of_examination(self):
new_exam = self.cleaned_data.get('date_of_examination')
try:
old_exam = Examination.objects.get(patient=self.cleaned_data.get('patient'))
except Examination.DoesNotExist:
return new_exam
if old_exam:
if old_exam.date_of_examination > new_exam:
raise forms.ValidationError("Second examination should take place after first examination")
return new_exam`
【问题讨论】:
-
你能展示你的模型吗?
-
是的,请分享您的模型,因为我认为我的回答可能是错误的!
-
我不太确定你想要达到什么目的,但我觉得我的回答是错误的,因为你的问题不是很明确!
-
当第二次考试的日期早于第一次考试的日期时,它应该给出错误。这就是我想要做的。
-
我认为这是最后一个 if 循环。 pat1.date_of_examination 的查询不正确。
标签: python django django-forms django-validation