[英]Flask_wtf - validate_on_submit() error on page load
Flask_wtf 的 validate_on_submit() 在第一次访问页面时永远不会为True
,因此它总是闪烁else
部分的(下面的代码)错误消息,它总是一个空的字典。
但是表单验证和提交工作正常 - 可以在有效帖子上看到成功的 flash 消息。 并且错误 flash 在有效提交后不会消失。
可重现的代码:
# necessary import stmts & other stuff
class MyForm(FlaskForm):
sub = StringField(validators=[DataRequired("Choose the title")])
body = TextAreaField(validators=[DataRequired(),Length(min=20)])
subm = SubmitField('Submit')
app.config['SECRET_KEY'] = 'my key'
@app.route('/', methods=['GET','POST'])
def index():
fo = MyForm()
flash('Submitted:'+str(fo.is_submitted())) # False on first time visit
#flash('After Validate:'+str(fo.validate()))
if fo.validate_on_submit():
ex = mytable(bodys = fo.body.data, subs = fo.sub.data)
# DB session add & commit stmt here
flash('Submitted','success')
return redirect(url_for('index'))
else:
flash('After val Errors:'+str(fo.errors))
return render_template('index.html',form=fo)
如果我取消注释 fo.validate()... 它会闪烁csrf_token': ['The CSRF token is missing.']
和其他数据需要错误消息,但如下所示 html 模板具有form.hidden_tag()
。 还使用了{{ form.csrf_token }}
而不是 hidden_tag()...没有成功。
<form method="POST" action="">
{{ form.hidden_tag() }}
{{ form.sub }}
{{ form.body }}
{{ form.subm }}
</form>
请帮助摆脱页面加载时的验证错误,谢谢
因此,在初始获取时,您不需要验证表单,因为还没有数据,只有在实际发布时才这样做,如下所示:
if request.method == 'POST':
if fo.validate_on_submit():
# DB session add & commit stmt here
flash('Submitted', 'success')
return redirect(url_for('index'))
else:
flash('After val Errors:' + str(fo.errors))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.