不要提交超过晚上11:59的时间

2024-05-21 05:41:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一张表格,上面有日期和时间。我目前有验证器,以确保过去的日期不能被使用,这是完美的工作。但是,我很难想象一个验证程序如何确保输入的时间不会超过晚上11:59。我加入了一个片段,我正在努力实现(我知道它没有工作的方式,它是在那里提供背景)。如果有人帮我,我会很感激的。你知道吗

你知道吗表单.py你知道吗

def validate_date1(value):
    if value < timezone.now():
        raise ValidationError('Date cannot be in the past')

def validate_date2(value):
    if value < timezone.now():
        raise ValidationError('Date cannot be in the past')

def present_date1(value):
    if value > '11:59 pm':
        raise ValidationError('Time cannot be past 11:59 pm')

def present_date2(value):
    if value > '11:59 pm':
        raise ValidationError('Time cannot be past 11:59 pm')

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, present_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, present_date2])
    lesson_weekly = forms.BooleanField(required=False)

Tags: ifvaluedefformsbevalidateclassraise
3条回答

所以,输入日期不能在过去,也不能在23:59之后,所以基本上它需要在今天的剩余时间内。你知道吗

怎么样:

import pytz

def date_is_not_past(dt):
    if dt < datetime.now(pytz.UTC):
        raise ValidationError('Date cannot be in the past')

def date_is_today(dt):
    if dt.date() != datetime.now(pytz.UTC).date():
        raise ValidationError('Date needs to be today')

您希望同时验证lesson_datetime_startlesson_datetime_end,而不是单独验证。只是检查一下时间是否不超过11:59pm并不能缩短它,因为这会使2019-05-04 11:00pm-2019-05-05 12:00am无效,即使它是从晚上11点开始的一个小时的正确间隔。你知道吗

为此,请在窗体中添加clean()方法:

def clean(self):
    cleaned_data = super().clean()
    if self.cleaned_data.get('lesson_datetime_start') \
            and self.cleaned_data.get('lesson_datetime_end') \
            and self.cleaned_data['lesson_datetime_start'] >= self.cleaned_data['lesson_datetime_end']:
        raise ValidationError({'lesson_datetime_end': "End time must be later than start time."})
    return cleaned_data

以同样的方式,您可以通过减去两个datetime字段并将它们与datetime.timedelta(hours=x)进行比较,来添加一个验证程序,说明课程的持续时间不超过某个预期的时间间隔(例如,不能长于4小时)。你知道吗

您也可以在模型中执行此操作,因此假设您有一个带有字段lesson_startlesson_endLesson模型:

def clean(self):
    if self.lesson_start and self.lesson_end and self.lesson_start >= self.lesson_end:
        raise ValidationError({'lesson_end': "End time must be later than start time."})

DateTimeField的验证器将获得一个datetime.datetime对象,而不是一个字符串。你知道吗

在这里,我们从datetime中提取时间成分,并将其与常量last possible time进行比较。你知道吗

import datetime

LAST_POSSIBLE_TIME = datetime.time(23, 59)

def validate_time(value):
    if value.time() > LAST_POSSIBLE_TIME:
        raise ValidationError('Time cannot be past 11:59 pm')

相关问题 更多 >