Process Data within Flask WTForms Submission

Viewed 152

I would like to reformat the data submitted via WTForms by utilizing the process_data function. I am able to successfully submit the form, however, the data is not modified in the output as expected. I've included a simplified example of my forms.py file below.

The goal of this form would be to input the value of "10,000" and return the string "10000".

from flask_wtf import FlaskForm
from wtforms import StringField

class SimpleForm(FlaskForm):
    price = StringField('price')

    def process_price(self, price):
        price.data = str(price).replace(',','')
1 Answers

process_data is a method on the base Field class (source). To use, you need to write a custom implementation of some Field class (StringField, in your instance) and override this method, then use this field in your form definition. For example:

from flask_wtf import FlaskForm
from wtforms import StringField

class CustomStringField(StringField):

    def process_data(self, data):
        self.data = str(data).replace(',', '')    

class SimpleForm(FlaskForm):
    price = CustomStringField('price')
Related