【问题标题】:Validate dates from DateTimeField are the same验证 DateTimeField 中的日期是否相同
【发布时间】:2019-03-11 19:33:53
【问题描述】:

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

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

【问题讨论】:

    标签: python django forms validation


    【解决方案1】:

    我不确定您为什么定义了clean2() 方法。 Django 并不期待这种方法,也永远不会调用它。

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

    【讨论】:

    • 我的错误,我更新了代码但现在得到错误,strptime() 参数 1 必须是 str,而不是 datetime.datetime
    • 是的。你为什么使用strptime()lesson_datetime_startend 已经是日期时间。
    • 我想确保日期时间的日期部分匹配,但不是时间部分,它们可能不同。我认为使用 strptime 获取日期时间的日期部分,可以让我只比较我想要的日期
    • strptime 用于将 text 转换为日期时间。它们已经是日期时间了。只需lesson_datetime_start.date()
    • 我现在有了,如果 course_datetime_start.date() != course_datetime_end.date() 和 course_datetime_start >= course_datetime_end:,但是 course_datetime_start 和 course_datetime_end 仍然有效,即使它们不匹配
    【解决方案2】:

    在您的方法clean() 中,尝试使用变量cleaned_data(您准备但从未实际使用)而不是self.cleaned_data

    这能解决你的问题吗?

    【讨论】:

    • 我的 clen() 方法有效,我的 clean2() 方法无效
    • 你在哪里调用你的方法clean2()
    • @Shoukran 您不能定义任意方法并希望它们被调用。如果它不是由某个父类调用的标准命名方法,那么您的代码将永远不会运行。
    • 我更新了我的代码,但课程日期时间开始和课程日期时间结束仍然有效,即使它们不匹配
    【解决方案3】:

    查看您更新的.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 个单独的 ifs:

    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
    

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

    【讨论】:

      猜你喜欢
      • 2014-12-28
      • 2021-12-27
      • 1970-01-01
      • 1970-01-01
      • 2015-10-28
      • 1970-01-01
      • 2011-04-24
      • 1970-01-01
      • 2020-12-27
      相关资源
      最近更新 更多