gpt4 book ai didi

python - 验证是否选中了 WTForms BooleanField

转载 作者:太空狗 更新时间:2023-10-30 02:02:48 25 4
gpt4 key购买 nike

我正在使用 Flask-WTForms 创建一个表单。

我正在使用 BooleanField,以便用户可以表明他们同意条款。

我无法在提交时验证 BooleanField 以确保它已被检查。我尝试过使用 Required()、DataRequired() 和自定义验证,但在每种情况下我都没有收到验证错误。

以下是应用程序的具体细节:

from flask import Flask, render_template, session, redirect, url_for, flash
from flask_wtf import Form
from wtforms import BooleanField, SubmitField
from wtforms.validators import Required, DataRequired
from flask_bootstrap import Bootstrap

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

bootstrap = Bootstrap(app)

class AgreeForm(Form):
agreement = BooleanField('I agree.', validators=[DataRequired()])
submit = SubmitField('Submit')


@app.route('/', methods=['GET', 'POST'])
def index():
form = AgreeForm()
if form.validate_on_submit():
agreement = form.agreement.data
if agreement is True:
flash('You agreed!')
return redirect(url_for('index', form=form))
form.agreement.data = None
agreement = False
return render_template('index.html', form=form)


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

这是 index.html 模板...

{% import "bootstrap/wtf.html" as wtf %}

{% block content %}
<div class="container">
{% for message in get_flashed_messages() %}
<div class="alert alert-warning">
<button type="button" class="close" data-dismiss="alert">&times;</button>
{{ message }}
</div>
{% endfor %}
{{ wtf.quick_form(form) }}
</div>
{% endblock %}

如有任何建议,我们将不胜感激。

最佳答案

对我有用——你确实需要使用 DataRequired()(Required 正在弃用):

from flask import Flask, render_template
from flask_wtf import Form
from wtforms import BooleanField
from wtforms.validators import DataRequired

app = Flask(__name__)
app.secret_key = 'STACKOVERFLOW'

class ExampleForm(Form):
checkbox = BooleanField('Agree?', validators=[DataRequired(), ])

@app.route('/', methods=['post', 'get'])
def home():
form = ExampleForm()
if form.validate_on_submit():
return str(form.checkbox.data)
else:
return render_template('example.html', form=form)


if __name__ == '__main__':
app.run(debug=True, port=5060)

模板:

<form method="post">
{{ form.hidden_tag() }}
{{ form.checkbox() }}
<button type="submit">Go!</button>
</form>

<h1>Form Errors</h1>
{{ form.errors }}

关于python - 验证是否选中了 WTForms BooleanField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38402850/

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