我目前正在使用 WTFORMS 创建动态选择字段,但是它从未提交并且验证失败并出现以下错误。
Not a valid choice
我的字段是这样创建的:
area = SelectField()
在视图中,我从数据库中获取选项,如下所示:
form = MytestForm()
form.area.choices = [(a.id, a.name) for a in Area.objects.all()]
但是,如果我创建静态选项,它会起作用。
我的猜测是Area.id
is a int
- 当数据从客户端返回时,它被视为string由 WTForms 除非将可调用对象传递给coerce
的关键字参数wtforms.fields.SelectField http://wtforms.readthedocs.org/en/latest/fields.html?highlight=fields.selectfield#wtforms.fields.SelectField构造函数:
area = SelectField(coerce=int)
或者,如果您使用 SQLAlchemy,您可以使用wtforms.ext.sqlalchemy.fields.QuerySelectField http://wtforms.readthedocs.org/en/latest/ext.html?highlight=wtforms.ext.sqlalchemy.fields.queryselectfield#wtforms.ext.sqlalchemy.fields.QuerySelectField (wtforms_sqlalchemy https://github.com/wtforms/wtforms-sqlalchemy如果您使用 WTForms 3+):
area = QuerySelectField(query_factory=Area.objects.all,
get_pk=lambda a: a.id,
get_label=lambda a: a.name)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)