【问题标题】:validate_on_submit is not working using WTF Formsvalidate_on_submit 无法使用 WTF 表单
【发布时间】:2021-07-19 05:10:58
【问题描述】:

当我在页面上注册时,我看到那些值被插入到数据库中,它正在将我重定向到代码中提到的登录功能,但我不明白为什么登录页面本身会被重定向每次我尝试登录时,它都应该被重定向到聊天功能。

I see that index function is working clearly

and also the values are getting inserted into database

But when I tried to login it's not getting redirected to the chat page

当我打印“login_form.validate_on_submit”时,结果总是错误的,所以我可以看到 validate_on_submit 函数有问题,但我不明白它是什么。

这是我在 application.py 中的登录功能:

@app.route('/login',methods=["GET","POST"])
def login():
    login_form=LoginForm()
    print(login_form)
    if login_form.validate_on_submit():
        user_object=User.query.filter_by(username=login_form.username.data)
        login_user(user_object)
        return redirect(url_for("chat"))
    return render_template("login.html", form=login_form)

这是 WTForm_Fields.py:

def invalid_credentials(form, field):
    """ Username and password checker """

    password = field.data
    username = form.username.data

    # Check username is invalid
    user_data = User.query.filter_by(username=username).first()
    print(user_data)
    if user_data is None:
        raise ValidationError("Username or password is incorrect")

    # Check password in invalid
    elif not pbkdf2_sha256.verify(password, user_data.hashed_pswd):
        raise ValidationError("Username or password is incorrect")

class LoginForm(FlaskForm):
    """login form"""
    username=StringField('username_label',validators=[InputRequired(message="username required")])
    password=PasswordField('password_label',validators=[InputRequired(message="Password Required"),invalid_credentials])

这是 login.html:

{% from 'form_helper.html' import displayField %}
{% extends 'prelogin-template.html'%}

{%block title%}Login{%endblock%}

{%block content%}
    <h2>Login now!</h2>
    <p>Enter your username/Password to start!!</p>

    <form action="{{ url_for('login') }}",method='POST'>
        {{displayField(form.username,"Username",autocomplete='off',autofocus=true)}}
        {{displayField(form.password,"Password")}}
        <div class="form-group">
            <input type="submit" value="Login" class="btn btn-warning">
        </div>
        {{ form.crsf_token }}

    </form>
{%endblock%}

这是 prelogin-template.html:

<!DOCTYPE html>
<html lang="en" dir="ltr">
    <head>
        <meta charset="utf-8">
        <title>{%block title%}{%endblock%}-Let's Chat </title>
    </head>
    <body>
    
    {% with messages=get_flashed_messages(with_categories=true) %}
        {% if messages %}    
            Category:{{ messages[0][0] }}
            {{messages[0][1]}}
        {% endif %}
    {% endwith %}
    {%block content%}
    
    {%endblock%}
</body>
</html>

这是 form_helper.html:

{% macro displayField(fieldName,placeholderValue) %}
<div class='form-group'>
   {{fieldName(class="form_control",placeholder=placeholderValue,**kwargs)}}
    <ul class="formError">
       {% for error in fieldName.errors %}
            <li>{{ error }}</li>
       {% endfor %}
    </ul>
</div>
{% endmacro %}

【问题讨论】:

  • 您可以尝试在html中的form标签下方打印{{form.errors}},看看提交时出现什么错误。
  • 我在表单助手模板中这样做了,如果我做错了什么,它会显示索引模板的错误,但不是登录模板,我已经添加了 form_helper 的代码,请检查.
  • 您应该在 login.html 中添加到此行上方 {{displayField(form.username,"Username",autocomplete='off',autofocus=true)}} 或将其添加到 app.py 中的登录功能中此 return render_template("login.html", form=login_form) 上方

标签: validation flask flask-sqlalchemy flask-wtforms wtforms


【解决方案1】:

在我看来,您的 form_helper.html、prelogin-template.html、login.html 和 WTForm_Fields.py 文件没有问题。但是,您的登录功能存在问题。我认为发生了数据库查询错误。一个建议是在用户对象的末尾简单地添加 .first()。当您提供 flask_sqlalchemy.BaseQuery 对象 作为参数时,flask_login 有时不会让用户登录。

尝试在 application.py 中的 Login Function 中执行此操作:

@app.route('/login',methods=["GET","POST"])
def login():
    login_form=LoginForm()
    print(login_form)
    if login_form.validate_on_submit():
        user_object=User.query.filter_by(username=login_form.username.data).first() #<--add here
        login_user(user_object)
        return redirect(url_for("chat"))
    return render_template("login.html", form=login_form)

这应该可以让用户顺利登录。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-01
    • 2023-03-15
    • 2018-03-15
    • 1970-01-01
    • 2012-05-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多