繁体   English   中英

验证是否选中了 WTForms BooleanField

[英]Validate that a WTForms BooleanField is checked

我正在使用 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 }}

您不必在表单中包含 DataRequired(),因为它没有意义,因为它是一个布尔值。 您必须通过说 if true 来获取 post 方法中传入的表单数据。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM