Form is never valid with WTForms

倖福魔咒の 提交于 2020-01-09 02:40:07

问题


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>

回答1:


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() }}
    ...

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

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.



来源:https://stackoverflow.com/questions/31925291/form-is-never-valid-with-wtforms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!