Flask_wtf - validate_on_submit() 页面加载错误

Flask_wtf - validate_on_submit() error on page load

Flask_wtf 的 validate_on_submit() 永远不会在第一次访问该页面时 True,所以它总是闪烁 else 部分的(下面的代码)始终为空字典的错误消息。

但表单验证和提交工作正常 - 可以在有效 post 上看到成功的闪现消息。有效提交后错误闪烁不会消失。

可重现代码:

# 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))