编程语言
首页 > 编程语言> > python – 我可以设置wtforms DateTimeField也只接受DateTime值吗?

python – 我可以设置wtforms DateTimeField也只接受DateTime值吗?

作者:互联网

我想让我的应用程序的用户输入Date或DateTime.有没有办法用单个字段实现这一目标?

dateCreated = DateField('Date created', validators[Required(message='Input must be of YYYY-MM-DD format.')])

sessionDate = DateTimeField('Date', validators=[Required(message='Input must be of YYYY-MM-DD HH:MM:SS format.')])

接受其中一个.有没有办法让一个领域接受?

解决方法:

这可以通过创建一个新的字段子类来完成,该子类将接受日期格式并返回datetime.datetime(但可以很容易地修改以返回datetime.date).

此实现基于wtforms.fields.DateTimeField(source)

class LenientDateTimeField(Field):

    def __init__(self, label=None, validators=None, formats=None, **kwargs):
        super(LenientDateTimeField, self).__init__(label, validators, **kwargs)
        if formats is None:
            self.formats = ['%Y-%m-%d %H:%M:%S', '%Y-%m-%d']
        else:
            self.formats = formats
        self.format = None

    def _value(self):
        if self.raw_data:
            return ' '.join(self.raw_data)
        else:
            return self.data and self.data.strftime(self.format) or ''

    def process_formdata(self, valuelist):
        if valuelist:
            date_str = ' '.join(valuelist)
            for fmt in self.formats:
                try:
                    self.data = datetime.datetime.strptime(date_str, fmt)
                    # If a datetime.date is required, do:
                    # datetime.datetime.strptime(date_str, fmt).date() 
                    self.format = format
                except ValueError:
                    self.data = None
                else:
                    break
            if self.data is None:
                message = 'Value did not match any of these formats: {}'.format(', '.join(self.formats))
                raise ValueError(self.gettext(message))

标签:python,wtforms,flask-wtforms
来源: https://codeday.me/bug/20190711/1432866.html