python – 验证是否已选中WTForms BooleanField
发布时间:2020-12-20 11:52:57 所属栏目:Python 来源:网络整理
导读:我正在使用Flask-WTForms创建一个表单. 我正在使用BooleanField,以便用户可以表明他们同意条款. 我无法在提交时验证BooleanField以确保它已被检查.我尝试使用Required(),DataRequired()和自定义验证,但在每种情况下我都没有收到验证错误. 以下是该应用程序的
我正在使用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">×</button> {{ message }} </div> {% endfor %} {{ wtf.quick_form(form) }} </div> {% endblock %} 我们将非常感激地收到任何建议. 解决方法
适合我 – 你需要使用DataRequired()(不推荐使用必需):
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 }} (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |