Skip to content Skip to sidebar Skip to footer

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):
   if data == None:
      return False
   if data == '':
      return False
   if data == []:
      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.

def is_filled(raw_data):
   try:
       value = raw_data[0]
       if value == '':
          return False
   except (IndexError, TypeError):
       return False
   return True

Tests:

>>> is_filled(None)
False
>>> is_filled([])
False
>>> is_filled(['',]) 
False

Post a Comment for "WTForms: Test Whether Field Is Filled Out"