首页 > 解决方案 > 在python wtforms中选择具有动态选择值的字段

问题描述

如何在 python wtforms 中创建具有动态选择的选择字段。我几乎阅读了所有出版的东西。我真的很理解这一点:

  1. 不要在课堂形式中添加选项,因为只学习一次,并且会以这种方式给你验证问题:category = SelectField('Category', coerce=int)
  2. 强制 int 以确保以这种方式正确读取它:category = SelectField('Category', choices=[], coerce=int)
  3. 以这种方式在端点上添加选项:form.category.choices = categories

现在,这就是问题所在:

  1. 如果不添加选项choices=[],则会引发错误 NoneType
  2. 如果您添加选项,它不会验证,因为“无效”

我的代码:

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]

有没有一种简单的方法可以实现这一目标?

标签: pythondrop-down-menuwtforms

解决方案


在实例化表单后设置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}


推荐阅读