peon
peon

Reputation: 1883

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')

Upvotes: 31

Views: 22057

Answers (2)

brevno
brevno

Reputation: 202

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'))

Upvotes: 5

dirn
dirn

Reputation: 20739

You are looking for the Optional validator.

start = DateField('Start Date', format='%m/%d/%Y', validators=(validators.Optional(),))

Upvotes: 53

Related Questions