Вопрос

My issue is very simple, here is a basic example:

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

I need to change the value sent by the user before the validators are called. What's the simplest way to do this without losing the benefits of using WTForms?

Это было полезно?

Решение 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().

Другие советы

All WTForm fields should support the filters keyword argument, which is a list of callables that will be run on the input data:

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])
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top