问题
I want to get the data for a user input date, or the current date if nothing is entered. I used WTForms to create a form with a date input, and override validate
to return True
if the date field has data. However, the form is always invalid even if I enter a date. Why isn't this working?
class ChooseDate(Form):
date = DateField(format='%m-%d-%Y')
def validate(self):
if self.date.data is None:
return False
else:
return True
@app.route('/index', methods=['GET', 'POST'])
def index():
date_option = ChooseDate()
print(date_option.date.data) # always None
if date_option.validate():
request_date = date_option.date.data
else:
request_date = datetime.today().date()
return render_template_string(template_string, form=date_option, date=request_date)
回答1:
You aren't overriding validate
correctly. validate
is what triggers the form to read the data and populate the data
attributes of the fields. You're not calling super
, so this never happens.
def validate(self):
res = super(ChooseDate, self).validate()
# do other validation, return final res
In this case there's no reason to override validate
, you're just trying to make sure data is entered for that field, so use the built-in InputRequired
validator. Using field validators will add error messages to the form as well.
from wtforms.validators import InputRequired
date = DateField(validators=[InputRequired()])
See the docs for more on validation.
Finally, you need to pass the form data to the form. If you were using the Flask-WTF extension's FlaskForm
, this would be passed automatically.
from flask import request
form = ChooseDate(request.form)
来源:https://stackoverflow.com/questions/35778199/wtforms-form-with-custom-validate-method-is-never-valid