Are you calling field.data variables before the validators for DateField?

My problem is very simple: here's a basic example:

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

      

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

+3


source to share


2 answers


Actualy "filters" were good, but that was not exactly what I was trying to do. I created my own field and it worked.

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 change the value directly in the user field, you need to override the _value ().

+2


source


All WTForm fields must support a filters

keyword argument, which is a list of invoked calls that will be made on the input:



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

      

+2


source







All Articles