Pregunta

I have this field in the WTForms form

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

When the field is submitted empty then form.name.data will, as expected, contain an empty string.

Is there some way to make it return None in instead of an empty string? It is just because it is very convenient to deal with null in the database like 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 take actions accordingly be it in the Python code on in the SQL code. The null with the coalesce solves that easily.

¿Fue útil?

Solución

There is the filters parameter to 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

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top