表单对 WTForms 永远无效 [英] Form is never valid with WTForms

查看:19
本文介绍了表单对 WTForms 永远无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用于登录的 Flask-WTF 表单.显然该表单永远不会有效,无论我输入什么,成功"都不会打印.为什么我的表单没有验证?

I have a Flask-WTF form for sign in. Apparently the form is never valid, no matter what I enter "success" is never printed. Why isn't my form validating?

class loginForm(Form):
    email = EmailField('email', validators=[InputRequired("Please enter your email address."), Email("Please enter a valid email address.")])
    password = PasswordField('password', validators=[InputRequired("Please enter your password.")])

@app.route('/sign-in', methods=['POST', 'GET'])
def signIn():
    form = loginForm(request.form)
    if form.validate_on_submit():
        print 'success'
        return redirect('/')
    return render_template('signIn.html')

<form method="POST" action="/sign-in">
    {{ form.email(placeholder='Email', class="textBox") }}
    {{ form.password(placeholder='Password', class="textBox") }}
    <button onclick="submit()">Sign In</button>
</form>

推荐答案

Flask-WTF 添加CSRF保护字段.如果不存在,CSRF 验证将失败,并且表单将无效.使用 form.hidden_​​tag() 在表单中包含任何隐藏字段(包括 CSRF 字段).

Flask-WTF adds a CSRF protection field. If it's not present, the CSRF validation will fail, and the form will be invalid. Use form.hidden_tag() to include any hidden fields in your form (including the CSRF field).

<form method="post">
    {{ form.hidden_tag() }}
    ...

<小时>

通常,如果表单未验证,您应该在调用 validate 后检查 form.errors 以查看错误.


In general, if a form is not validating, you should check form.errors after calling validate to see what's wrong.

您没有看到错误,因为您没有呈现该字段(或在这种情况下呈现任何字段的错误,但这对解决此问题没有帮助).如果您在调试器中运行并检查 form.errors,您会发现确实存在 "CSRF 令牌丢失" 错误.

You don't see the error since you're not rendering that field (or rendering the errors for any fields in this case, but that wouldn't help with this issue). If you ran in a debugger and examined form.errors, you would see that there was indeed a "CSRF token missing" error.

这篇关于表单对 WTForms 永远无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆