how to implement not-required DateField using Flask-WTF
Asked Answered
S

2

31

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')
Sneeze answered 4/1, 2015 at 14:18 Comment(0)
G
5

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'))
Gilda answered 21/12, 2018 at 16:31 Comment(2)
I cannot verify that there would be any problems just using validators.Optional().Anthrax
Finally! Thank you for this. I can confirm Optional did not work for me, still returned not a valid date value. This works flawlessly.Sage
R
53

You are looking for the Optional validator.

start = DateField('Start Date', format='%m/%d/%Y', validators=(validators.Optional(),))
Roney answered 4/1, 2015 at 15:47 Comment(0)
G
5

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'))
Gilda answered 21/12, 2018 at 16:31 Comment(2)
I cannot verify that there would be any problems just using validators.Optional().Anthrax
Finally! Thank you for this. I can confirm Optional did not work for me, still returned not a valid date value. This works flawlessly.Sage

© 2022 - 2024 — McMap. All rights reserved.