how to implement not-required DateField using Flask-WTF
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'))