3

我的问题很简单,这是一个基本的例子:

class F(Form):
  date_test = DateField('Test', validators=[Required()], format='%d/%m/%Y')

我需要在调用验证器之前更改用户发送的值。在不失去使用 WTForms 的好处的情况下,最简单的方法是什么?

4

2 回答 2

2

Actualy "filters" was nice but it was not exactly what I was trying to do. I made a custom field and it's working.

class MyDateField(DateField):
    def __init__(self, label='', validators=None, transform_data=False, **kwargs):
        super(MyDateField, self).__init__(label, validators, **kwargs)
        self.transform_data = transform_data

    def process_formdata(self, valuelist):
      if self.transform_data:
        data = str(valuelist[0])
        # transform your data here. (for example: data = data.replace('-', '.'))

      super(MyDateField, self).process_formdata([data])

class F(Form):
    date_test = MyDateField('Test', validators=[Required()], format='%d/%m/%Y', transform_data=True])

If you want to modify the value directly in the user field you need to override _value().

于 2013-01-27T01:11:08.803 回答
2

所有 WTForm 字段都应该支持filters关键字参数,这是一个将在输入数据上运行的可调用对象列表:

def transform_data(data):
    # do something with data here
    return data

class F(Form):
    date_test = DateField('Test', validators=[Required()], format='%d/%m/%Y',
                              filters=[transform_data])
于 2013-01-26T18:19:54.310 回答