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.
Simply the str function can be used to perform this particular task because, None also evaluates to a “False” value and hence will not be selected and rather a string converted false which evaluates to empty string is returned.
Definition and Usage. The None keyword is used to define a null value, or no value at all. None is not the same as 0, False, or an empty string.
Use the boolean OR operator to convert None to an empty string in Python, e.g. result = None or "" . The boolean OR operator returns the value to the left if it's truthy, otherwise the value to the right is returned. Since None is a falsy value, the operation will return "" . Copied!
The value null represents the absence of any object, while the empty string is an object of type String with zero characters. If you try to compare the two, they are not the same.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With