创建错误消息日期字段

时间:2017-03-09 19:43:07

标签: python django django-forms django-validation

我想为以下表单创建错误消息:

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`

2 个答案:

答案 0 :(得分:0)

def clean_date_of_examination(self):
    # Where 'data' is used?
    date_of_exam = self.cleaned_data['date_of_examination']

    try:
        pat1 = Patient.object.get(examination__number_of_examination=1, date_of_examination=date_of_exam)
    except Patiens.DoesNotExist:
        # Patient 1 with given query doesn't exist. Handle it!
    try:
        pat2 = Patient.object.get(examination__number_of_examination=2, date_of_examination=date_of_exam)
    except Patiens.DoesNotExist:
        # Patient 2 with given query doesn't exist. Handle it!

    if pat2.date_of_examination < pat1.date_of_examination:
         raise forms.ValidationError("Second examination should take place after first examination")`
    return data`

答案 1 :(得分:0)

def clean_date_of_examination(self):
    new_exam = self.cleaned_data.get('date_of_examination')
    old_exam = Examination.objects.get(patient = self.cleaned_data.get('Patient'))
    if old_exam:
        if old_exam.date_of_examination > new_exam.date_of_examination:
            raise forms.ValidationError("Second examination should take place after first examination")
    return data