Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to implement not-required DateField using Flask-WTF

I want a DateField which is optional, but I got a "Not a valid date value" error if leave it empty

I add some logs in the source code of wtforms, and found formdata.getlist(self.name) returns [u''] for this DateField

The code of my form:

from wtforms import BooleanField, TextField, TextAreaField, PasswordField, validators, HiddenField, DateField, SelectField from flask_wtf import Form  class EmployeeForm(Form):     id = HiddenField('id')     title = TextField('Title')     start = DateField('Start Date', format='%m/%d/%Y') 
like image 213
peon Avatar asked Jan 04 '15 14:01

peon


People also ask

What is StringField?

StringField (default field arguments)[source]¶ This field is the base for most of the more complicated fields, and represents an <input type="text"> .

What are validators class of WTForms in flask?

A validator simply takes an input, verifies it fulfills some criterion, such as a maximum length for a string and returns. Or, if the validation fails, raises a ValidationError . This system is very simple and flexible, and allows you to chain any number of validators on fields.


2 Answers

You are looking for the Optional validator.

start = DateField('Start Date', format='%m/%d/%Y', validators=(validators.Optional(),)) 
like image 111
dirn Avatar answered Sep 18 '22 23:09

dirn


Quite and old topic, but someone might still run into the same problem, so I'll put my possible answer for that. Adding validators.Optional() does not help here, because the field is marked as error earlier during the processing stage.
You can patch the processor's behaviour like this:

class NullableDateField(DateField):     """Native WTForms DateField throws error for empty dates.     Let's fix this so that we could have DateField nullable."""     def process_formdata(self, valuelist):         if valuelist:             date_str = ' '.join(valuelist).strip()             if date_str == '':                 self.data = None                 return             try:                 self.data = datetime.datetime.strptime(date_str, self.format).date()             except ValueError:                 self.data = None                 raise ValueError(self.gettext('Not a valid date value')) 
like image 23
brevno Avatar answered Sep 21 '22 23:09

brevno