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')
StringField (default field arguments)[source]¶ This field is the base for most of the more complicated fields, and represents an <input type="text"> .
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.
You are looking for the Optional
validator.
start = DateField('Start Date', format='%m/%d/%Y', validators=(validators.Optional(),))
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'))
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