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

时间:2015-11-15 23:41:41

标签: python flask-wtforms wtforms

我想让我的应用程序的用户输入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.')])

接受其中一个。有没有办法让一个字段接受?

1 个答案:

答案 0 :(得分:0)

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

此实现基于wtforms.fields.DateTimeFieldsource

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))