验证DateTimeField中的日期是否相同

时间:2019-03-11 19:33:53

标签: python django forms validation

我有一个表格,我试图添加一种干净的方法以确保输入的日期相同。即使日期不相同,表单也恰好通过了。我相信问题出在我的干净方法上,但是由于它没有传递错误,所以我不确定是什么引起了问题。我将不胜感激。

class LessonForm(forms.ModelForm):
    lesson_instrument = forms.ChoiceField(choices=instrument_list, widget=forms.Select(attrs={'class' : 'form-control', 'required' : 'True'}))
    lesson_datetime_start = forms.DateTimeField(input_formats=['%Y-%m-%d %I:%M %p'], widget=forms.DateTimeInput(attrs={'class': 'form-control', 'placeholder':'YYYY-MM-DD Hour:Minute am/pm'}), validators=[validate_date1])
    lesson_datetime_end = forms.DateTimeField(input_formats=['%Y-%m-%d %I:%M %p'], required=False, widget=forms.DateTimeInput(attrs={'class': 'form-control', 'placeholder':'YYYY-MM-DD Hour:Minute am/pm'}), validators=[validate_date2])
    lesson_weekly = forms.BooleanField(required=False)

    class Meta:
        model = Lesson
        fields = ('lesson_instrument', 'lesson_datetime_start', 'lesson_datetime_end', 'lesson_weekly')

    def clean(self):
        cleaned_data = super().clean()
        lesson_datetime_start = self.cleaned_data.get("lesson_datetime_start")
        lesson_datetime_end = self.cleaned_data.get("lesson_datetime_end")
        if lesson_datetime_start.date() != lesson_datetime_end.date() and lesson_datetime_start >= lesson_datetime_end:
            raise ValidationError('Dates have to be the same and end time must be later than start time')
        return cleaned_data

3 个答案:

答案 0 :(得分:1)

我不确定您为什么定义了clean2()方法。 Django不希望使用该方法,也永远不会调用它。

您需要将所有逻辑都放在同一方法中,即clean()

答案 1 :(得分:0)

在方法clean()中,尝试使用变量cleaned_data(您已准备但从未实际使用过)代替self.cleaned_data

这可以解决您的问题吗?

答案 2 :(得分:0)

查看更新的.clean()方法:

def clean(self):
    cleaned_data = super().clean()
    lesson_datetime_start = self.cleaned_data.get("lesson_datetime_start")
    lesson_datetime_end = self.cleaned_data.get("lesson_datetime_end")
    if lesson_datetime_start.date() != lesson_datetime_end.date() and lesson_datetime_start >= lesson_datetime_end:
        raise ValidationError('Dates have to be the same and end time must be later than start time')
    return cleaned_data

只有同时给出两个条件,该错误才会发生,这似乎与您要查找的内容不符。

我建议您将if语句中的逻辑分为2个独立的if

def clean(self):
    cleaned_data = super().clean()
    lesson_datetime_start = cleaned_data.get("lesson_datetime_start")
    lesson_datetime_end = cleaned_data.get("lesson_datetime_end")
    print('lesson_datetime_start', lesson_datetime_start)
    print('lesson_datetime_end', lesson_datetime_end)

    if lesson_datetime_start.date() != lesson_datetime_end.date():
        raise ValidationError('Dates have to be the same.')

    if lesson_datetime_start >= lesson_datetime_end:
        raise ValidationError('End time must be later than start time.')

    return cleaned_data

我认为这更接近于验证的真实意图。对您有用吗?