【问题标题】:validate_on_submit() not working in Flask. What should I do?validate_on_submit() 在 Flask 中不起作用。我该怎么办?
【发布时间】:2021-11-26 06:34:40
【问题描述】:

我是 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)

这是来自 My 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>

【问题讨论】:

    标签: python flask jinja2 flask-wtforms


    【解决方案1】:

    作为一个新的烧瓶用户和简单的烧瓶使用,你应该不需要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 实例访问数据。

    【讨论】:

    • 你是天才!!!多谢!!!!我应该在我的视图函数中实例化我的表单。之所以使用app_context和text_request_context,是因为之前遇到的报错信息。
    猜你喜欢
    • 1970-01-01
    • 2020-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-11
    • 2013-10-01
    • 2022-08-07
    相关资源
    最近更新 更多