Wtforms: Test Whether Field Is Filled Out
I'm having trouble with what I thought would be a very simple task in WTForms: checking to see if a field has had any data entered in it. It seems that the data method returns diff
Solution 1:
In raw_data
, values for a form field are collected in a list.
You want to work with data
because its value is processed to its python representation. Most fields subclassing wtforms.fields.core.Field
implements their own process_formdata
method which fulfills this.
Start by implementing a helper function that checks field data like so:
def is_filled(data):
ifdata == None:
return False
ifdata == '':
return False
ifdata == []:
return False
return True
Note that data starts out set to the default value if a default value is specified in the field schema. In this case using raw_data
is more correct.
defis_filled(raw_data):
try:
value = raw_data[0]
if value == '':
returnFalseexcept (IndexError, TypeError):
returnFalsereturnTrue
Tests:
>>> is_filled(None)
False>>> is_filled([])
False>>> is_filled(['',])
False
Post a Comment for "Wtforms: Test Whether Field Is Filled Out"