gpt4 book ai didi

python-3.x - 为什么当验证器条件不满足时 wtforms 不产生错误?

转载 作者:行者123 更新时间:2023-12-05 05:01:20 26 4
gpt4 key购买 nike

所以我正在处理一个有两个输入和一个检查条件的表单。如果不满足检查条件,则引发错误。否则取数据库中的值。下面给出的是我的 forms.py 脚本。

from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, validators

# Define QuoteForm below
class QuoteForm(FlaskForm):
# qauthor = StringField("Quote Author",[validators.DataRequired(message="This field is required"),validators.Length(min =3, max =100,message = "Field must be between 3 and 100 characters long.")])
qauthor = StringField("Quote Author",validators=[validators.DataRequired(message="This field is required"),validators.Length(min =3, max =100,message = "Field must be between 3 and 200 characters long.")])
qstring = StringField("Quote",validators=[validators.DataRequired(message="This field is required"),validators.Length(min =3, max =200,message = "Field must be between 3 and 200 characters long.")])
submit = SubmitField(" Add Quote")

如您所见,两个字段的最小长度都应大于 3。我也在 HTML 页面 addquote.html

中捕获错误
<body>
<h2>QuoteForm</h2>
<form action="", method="post">
<p>
{{form.qauthor.label}} : {{form.qauthor}}<br>
{%for error in form.qauthor.errors%}
<span style="color: red;">[{{ error }}]</span><br>

{% endfor %}

</p>
<p>
{{form.qstring.label}} : {{form.qstring}}<br>
{%for error in form.qstring.errors%}
<span style="color: red;">[{{ error }}]</span><br>
{% endfor %}
</p>

<p>{{form.submit}}</p>
</form>
</body>

我在我的 flask 函数中调用表单。给出如下。

@app.route('/addquote/', methods=['GET', 'POST'])
def add_quote():
form = QuoteForm()
if form.is_submitted():
breakpoint()
result = request.form
qqauthor = result['qauthor']
qqstring = result['qstring']
add_tab = Quotes(quoteauthor=qqauthor,quotestring=qqstring)
db.session.add(add_tab)
db.session.commit()
return render_template("addquote_confirmation.html")

return render_template("addquote.html",form=form)
  • 现在我传递的输入是 Quote Author to be: "AT" 和 Quote to be: "This is a beautiful world"
  • 引用作者为:*"AT" 引用为:"RT"

我在我的 forms.py 中提到的条件最小长度为 3 的这两种情况下都没有收到错误。为什么错误没有出现或验证没有发生?依赖:flask_wtf=='0.14.3'flask=='1.0.2'

最佳答案

您需要调用表单的validate() 方法。调用 validate_on_submit() 更方便,这是检查事件请求是否提交(POST、PUT、PATCH 或 DELETE)以及表单数据是否有效的快捷方式(see docs) .

@app.route('/addquote/', methods=['GET', 'POST'])
def add_quote():
form = QuoteForm()
if form.validate_on_submit():
breakpoint()
add_tab = Quotes(quoteauthor=form.qqauthor.data, quotestring=form.qqstring.data)
db.session.add(add_tab)
db.session.commit()
return render_template("addquote_confirmation.html")

return render_template("addquote.html",form=form)

下面是简单的完整示例代码,没有数据库,只是打印出表单的数据。

app.py

from flask import Flask, render_template, url_for
from flask_wtf import FlaskForm
from markupsafe import Markup
from wtforms import StringField, SubmitField, validators


class QuoteForm(FlaskForm):
author = StringField(
"Quote Author",
validators=[
validators.DataRequired(message="This field is required"),
validators.Length(min=3, max=100, message="Field must be between 3 and 200 characters long.")
]
)
quote = StringField(
"Quote",
validators=[
validators.DataRequired(message="This field is required"),
validators.Length(min=3, max=200, message="Field must be between 3 and 200 characters long.")
]
)
submit = SubmitField(" Add Quote")


app = Flask(__name__)
app.config['SECRET_KEY'] = 'MY SECRET KEY'


@app.route('/', methods=['GET'])
def index():
_quote_url = url_for('add_quote')
return Markup(f'<a href="{_quote_url}">Add Quote</a')


@app.route('/add-quote/', methods=['GET', 'POST'])
def add_quote():
form = QuoteForm()
if form.validate_on_submit():
print(f'Author: {form.author.data}')
print(f'Quote: {form.quote.data}')
return "Quote form is validated"

return render_template("add-quote.html", form=form)


if __name__ == '__main__':
app.run()

add-quote.html

<body>
<h2>QuoteForm</h2>
<form action="" method="post">
{{ form.csrf_token }}
<p>
{% for error in form.errors %}
<span style="color: red;">[{{ error }}]</span><br>
{% endfor %}
</p>
<p>
{{ form.author.label }} : {{ form.author }}<br>
{% for error in form.author.errors %}
<span style="color: red;">[{{ error }}]</span><br>

{% endfor %}

</p>
<p>
{{ form.quote.label }} : {{ form.quote }}<br>
{% for error in form.quote.errors %}
<span style="color: red;">[{{ error }}]</span><br>
{% endfor %}
</p>

<p>{{ form.submit }}</p>
</form>
</body>

关于python-3.x - 为什么当验证器条件不满足时 wtforms 不产生错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62750892/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com