簡體   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