我是Flask的新手。
validate_on_submit()不起作用,我也不知道app.app_context()和app.test_request_context(。
我唯一想做的就是验证我的表格,我不明白为什么它不起作用。
这是我的主要.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">×</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>
作为一个新的烧瓶用户和简单的烧瓶用法,您不应该需要app_context
和test_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
实例上访问数据。