Get None from Fields Data Instead of an Empty String

I have this field in the form of WTForms

 name = StringField('Name', validators = [Optional(), Length(max = 100)]) 

When a field is sent empty, form.name.data will, as expected, contain an empty string.

Is there a way to make it return None instead of an empty string? This is simply because it is very convenient to deal with null in the database, as in this update :

 update t set name = coalesce(%(name)s, name), other = coalesce(%(other)s, other) 

With the above code, I don’t need to check if the field is empty or not, and accordingly execute the actions in Python code in SQL code. null with coalesce solves this easily.

+6
source share
1 answer

There is a filters parameter for the Field constructor

 name = StringField( 'Name', validators = [Optional(), Length(max = 100)], filters = [lambda x: x or None] ) 

http://wtforms.readthedocs.org/en/latest/fields.html#the-field-base-class

+14
source

All Articles