首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >validate_on_submit()在烧瓶中不起作用。我该怎么办?

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

Stack Overflow用户
提问于 2021-10-06 03:52:22
回答 1查看 52关注 0票数 0

我是新来Flask的。

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

我唯一想做的就是让我的表单验证我不知道为什么它不能工作。

这是我的main.py

代码语言:javascript
复制
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中的代码

代码语言:javascript
复制
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

代码语言:javascript
复制
<!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>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-10-06 08:37:13

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

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

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

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

main.py应该看起来像这样(我测试过了):

代码语言:javascript
复制
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实例访问数据。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69459622

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档