Python form.validate_on_submit()始终为假

时间:2019-05-20 07:11:37

标签: python flask flask-wtforms

我正在使用flask_wtf

这是我的登录表格

from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField
from wtforms.validators import DataRequired, Length


class LoginForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired()])
    password = PasswordField('Password', validators=[DataRequired(), Length(8, 128)])
    remember = BooleanField('Remember me')
    submit = SubmitField('Log in')

这是我的login.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>login</title>
</head>
<body>
<form method="POST" action="">
    {{ form.csrf_token }}
    {{ form.username.label }}<br>{{ form.username }}<br>
    {{ form.password.label }}<br>{{ form.password }}<br>
    {{ form.remember }}{{ form.remember.label }}<br>
    {{ form.submit }}<br>
</form>
</body>
</html>

和我的app.py

from flask import Flask, render_template
from forms import LoginForm

app = Flask(__name__)
app.secret_key = 'learnflask'
@app.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        username = form.username.data
        print(username)
    return render_template('login.html', form=form)


if __name__ == '__main__':
    app.run(debug=True)

我的问题是用户名不打印。似乎未提交登录表单,form.validate_on_submit()为假。

2 个答案:

答案 0 :(得分:1)

对于password字段,您已设置验证程序以检查长度是否在8到128之间。如果用户输入的密码长度较小或较大,则验证将失败。我认为这就是form.validate_on_submit()始终为假的原因。

我已经在模板中显示了错误消息并得到了错误。

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>login</title>
    <style>
        .validation_error{
        color: red;
    }
    </style>
</head>
<body>
<form method="POST" action="">
    {{ form.csrf_token }}
    {{ form.username.label }}<br>{{ form.username }}<span class="validation_error">{{ ', '.join(form.username.errors) }}</span><br>
    {{ form.password.label }}<br>{{ form.password }}<span class="validation_error">{{ ', '.join(form.password.errors) }}</span><br>
    {{ form.remember }}{{ form.remember.label }}<span class="validation_error">{{ ', '.join(form.remember.errors) }}</span><br>
    {{ form.submit }}<br>
</form>
</body>
</html>

app.py

from flask import Flask, render_template
from forms import LoginForm

app = Flask(__name__)
app.secret_key = 'learnflask'
@app.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        username = form.username.data
        return username
    return render_template('login.html', form=form)

输出:

有效输入:

valid input

无效输入:

invalid input

答案 1 :(得分:0)

form.validate_on_submit()为false,因为您尚未将request.form对象添加到LoginForm()

form = LoginForm(request.form)