如何使用wtforms列出BooleanField [英] How to make a list of BooleanField using wtforms
问题描述
我的目标是从数据库中查询用户列表,然后在每个人的姓名旁边添加一个BooleanField.可以检查每个人是否将其提交到表单.我试过使用SelectMultipleField,但它似乎只提交一个值,而FieldList确实没有示例,因此我不确定它们是否是我想要的.我是WTForms的新手,我不确定要使用哪种最佳选择.
示例:
我将假设您正在使用Flask-SQLAlchemy来处理数据模型,因为您没有提到如何访问数据库./p>
定义如下的表格:
class ExampleForm(Form):用户= QuerySelectMultipleField('用户',query_factory = lambda:User.query.all(),widget = widgets.ListWidget(prefix_label = False),option_widget = widgets.CheckboxInput())提交= SubmitField('提交')
将为每个用户生成一个复选框列表,然后可以根据需要进行处理.呈现表单的模板可以是:
< form action =" method ="POST">{{form.csrf_token}}{{form.user}}{{form.submit}}</form>
并且路线代码将与以下内容类似:
@ app.route('/',Methods = ['post','get'])def home():形式= ExampleForm()如果form.validate_on_submit():返回"{}".format(form.user.data)返回render_template('example.html',form = form)
My goal is to query a list of users from a database then have a BooleanField next to each person's name. Each person can be checked whether they will be submitted to the form or not. I have tried using SelectMultipleField, but it seems to only submit one value, and FieldList really has no examples so I am not sure if they may be what I am looking for or not. I am new to WTForms and I am not sure what is the best option to use for what I am trying to do.
Example:
I'm going to assume you're using Flask-SQLAlchemy to handle your data model because you make no mention of how you're accessing you database.
A form defined like:
class ExampleForm(Form):
user = QuerySelectMultipleField(
'User',
query_factory=lambda: User.query.all(),
widget=widgets.ListWidget(prefix_label=False),
option_widget=widgets.CheckboxInput()
)
submit = SubmitField('Submit')
Will generate a list of checkboxes for each user, which then can be handled as required. The template to render the form could then just be:
<form action="" method="POST">
{{ form.csrf_token }}
{{ form.user }}
{{ form.submit }}
</form>
And the route code would just be along the lines of:
@app.route('/', methods=['post','get'])
def home():
form = ExampleForm()
if form.validate_on_submit():
return "{}".format(form.user.data)
return render_template('example.html', form=form)
这篇关于如何使用wtforms列出BooleanField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!