具有自定义验证方法的WTForms表单永远无效 [英] WTForms form with custom validate method is never valid
问题描述
我想获取用户输入日期或当前日期(如果未输入任何内容)的数据.我使用WTForms创建了一个带有日期输入的表单,如果日期字段中包含数据,则覆盖 validate
以返回 True
.但是,即使输入日期,该表格也始终无效.为什么这行不通?
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)
推荐答案
您没有正确覆盖 validate
. validate
是触发表单读取数据并填充字段的 data
属性的原因.您不是在呼叫 super
,所以这永远不会发生.
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
在这种情况下,没有理由覆盖 validate
,您只是想确保为该字段输入了数据,因此请使用内置的 InputRequired
验证器.使用字段验证器也会向表单中添加错误消息.
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.
最后,您需要将表单数据传递给表单.如果您使用的是 Flask-WTF 扩展的 FlaskForm
,这将自动传递.
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)
这篇关于具有自定义验证方法的WTForms表单永远无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!