Monday, 30 April 2012

WTForms - filtering values

WTForms - using filters on Field items

Pretty basic- the WTForms documentation shows that field elements can be supplied filter methods these can be defined and used as in the example below:
Note: The filter will multiple the value by 100 then replace the last two digits with zeros:
import re

def filter_field(value):
   return re.sub('\d{2}$','00',value)

class MyForm(Form):
   field_one = TextField('Field 1',validators=[validators.Regexp('^[0-9]*)',
                             message='Must be an integer')],
                             filters=[lambda x: x*100, filter_field])

When a MyForm object is instantiated and processed the filters will be run in order they appear in the argument list. Note the list of filters contains two different types an 'inline' function defined in Python using 'lambda' and a defined function.
The filters will be applied when processing the form:
j_env = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))

class IndexPage(webapp2.RequestHandler):  
   def post(self):
       aforminstance = MyForm(formdata=self.request.POST)

app = webapp2.WSGIApplication( [ ('/', IndexPage) ], debug=True )

No comments:

Post a Comment