validate_on_submit() 在烧瓶中不起作用。我应该怎么办?

validate_on_submit() not working in Flask. What should I do?

我是 Flask 新手。

validate_on_submit() 不工作,我也不知道 app.app_context() 和 app.test_request_context() 在我的代码中做了什么。

我唯一想做的就是验证我的表单我无法弄清楚为什么它不起作用。

这是我的main.py

from flask import Flask, render_template, request, flash
from the_first_wt_form import MyForm

app = Flask(__name__)
app.config['SECRET_KEY'] = '934kegn298u54kjgnjdkrbg9u939'


with app.app_context():
    with app.test_request_context():
        a_form = MyForm()


@app.route('/', methods=['GET', 'POST'])
def home():
    if request.method == "POST":
        name = request.form['name']
        print(name)
        email = request.form['email']
        print(email)
        passwrd = request.form['password']
        print(passwrd)
        con = request.form['confirm']
        print(con)
        if a_form.validate_on_submit():
            print("Good job")
            name = request.name.data
            print(name)
        else:
            print('We messed up')

        if a_form.errors != {}:
            for err in a_form.errors.values():
                print(f"There was an error with creating user: {err}")
                flash(f"There was an error with creating user: {err}", category='danger')
    return render_template('mynewhome.html', form=a_form)

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

这是我的 wt_form.py

中的代码
from wtforms import StringField, PasswordField, validators, SubmitField 

from flask_wtf import FlaskForm



class MyForm(FlaskForm):
    name = StringField('name', [validators.Length(min=4, max=25), validators.DataRequired()])
    email = StringField('Email Address', [validators.Length(min=6, max=35), validators.Email()])
    password = PasswordField('New Password', [
        validators.DataRequired(),
        validators.EqualTo('confirm', message='Passwords must match')
    ])
    confirm = PasswordField('Repeat Password')
    submit = SubmitField('Register')

最后这是 mynewhome.html

<!DOCTYPE html> <html lang="en"> <head>
    <meta charset="UTF-8">
    <title>How are you?</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-uWxY/CJNBR+1zjPWmfnSnVxwRheevXITnMqoEIeG1LJrdI0GlVs/9cVSyPYXdcSF" crossorigin="anonymous">

</head> <body>

<h1> Hello BRo </h1> <br><br> {% with messages = get_flashed_messages(with_categories = true) %}
    {% if messages %}
        {% for category, message in messages %}
            <div class="alert alert--{{ category }}">
                <button type="button" class="m1-2 mb-1 close" data-dismiss="alert" aria-label="Close">
                    {{ message }}
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
        {% endfor %}
    {% endif %}

{% endwith %} <br><br>

<div class="container">
    <form method="POST" action="/" class="form-register">
        {{ form.hidden_tag() }}
        {{ form.name.label }} {{ form.name(class = "form-control", Placeholder = "Usern Name") }}
        {{ form.email.label }} {{ form.email(class = "form-control", Placeholder = "Email Address") }}
        {{ form.password.label }} {{ form.password(class = "form-control", Placeholder = "Password") }}
        {{ form.confirm.label }} {{ form.confirm(class = "form-control", Placeholder = "Confirm Password") }}
        <br>
         {{ form.submit(class = "btn btn-lg btn-block btn-primary") }}
    </form> </div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-kQtW33rZJAHjgefvhyyzcGF3C5TFyBQBA13V1RKPf4uH+bwyzQxZ6CmMZHmNBEfJ" crossorigin="anonymous"></script> </body> </html>

作为一个新的flask用户和简单的flask使用,你应该不需要app_contexttest_request_context。您可以查看文档以了解它们,但在这种情况下不需要它们。

您必须在视图函数中实例化您的表单home

仅在验证后才使用表单数据也是一种更好的做法,因为您永远不知道用户在您的表单中输入了什么。

在导入中您正在导入 the_first_wt_form 但您说您的文件名为 wt_form 所以我进行了适当的更改。但是根据您的模块设置,它可能是错误的。

main.py 应该是这样的(我测试过):

from flask import Flask, render_template, request, flash
from wt_form import MyForm

app = Flask(__name__)
app.config['SECRET_KEY'] = '934kegn298u54kjgnjdkrbg9u939'


@app.route('/', methods=['GET', 'POST'])
def home():
    a_form = MyForm()
    if request.method == "POST":
        if a_form.validate_on_submit():
            print("Good job")
            name = a_form.name.data
            print(name)
            # (...)
        else:
            print('We messed up')

            if a_form.errors != {}:
                for err in a_form.errors.values():
                    print(f"There was an error with creating user: {err}")    
                    flash(f"There was an error with creating user: {err}", category='danger')
    return render_template('mynewhome.html', form=a_form)

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

请注意,您可以直接从 a_form 实例而不是 request 实例访问数据。