python - 在python wtforms中选择具有动态选择值的字段
问题描述
如何在 python wtforms 中创建具有动态选择的选择字段。我几乎阅读了所有出版的东西。我真的很理解这一点:
- 不要在课堂形式中添加选项,因为只学习一次,并且会以这种方式给你验证问题:
category = SelectField('Category', coerce=int)
- 强制 int 以确保以这种方式正确读取它:
category = SelectField('Category', choices=[], coerce=int)
- 以这种方式在端点上添加选项:
form.category.choices = categories
现在,这就是问题所在:
- 如果不添加选项choices=[],则会引发错误 NoneType
- 如果您添加选项,它不会验证,因为“无效”
我的代码:
author=SelectField('author', choices=[], default=1)
Cursor.execute(source, 1)
choices_source=Cursor.fetchall()
form.source.choices= [(c[0], c[1]) for c in choices_source]
有没有一种简单的方法可以实现这一目标?
解决方案
在实例化表单后设置choices
属性似乎有效:
import wtforms
from werkzeug.datastructures import MultiDict
class AuthorForm(wtforms.Form):
author = wtforms.SelectField('author', coerce=int, default=1)
authors = [(1, 'Amy Tan'), (2, 'Michael Chabon')]
af = AuthorForm()
af.author.choices = authors
for field in af:
print(field)
af = AuthorForm(formdata=MultiDict([('author', '1')]))
af.author.choices = authors
if not af.validate():
print(af.errors)
else:
print(af.data)
输出:
<select id="author" name="author"><option selected value="1">Amy Tan</option><option value="2">Michael Chabon</option></select>
{'author': 1}
推荐阅读
- autodesk-forge - 如何让标记的核心扩展自动关闭它创建的文本区域?
- system - 来自不同公司的多个用户使用相同的服务
- jdbc - Confluent Kafka-connect-JDBC 连接器在 kafka 主题中显示十六进制数据
- javascript - 检测隐藏选择元素上的更改事件
- sql - 递归 CTE 返回超出范围的值
- r - t.test 在两组之间,一组有 4 个观察值,另一组有 2 个观察值
- java - 检查乘法表数组
- c - 通过没有大 if/else 块的 Lua 元表公开 C 函数/变量?
- php - 根据php中的值更改样式颜色的值
- complex-event-processing - 过滤 Siddhi 中的先前事件