不是动态选择字段 WTFORMS 的有效选择 [英] Not a Valid Choice for Dynamic Select Field WTFORMS
问题描述
我目前正在使用 WTFORMS 创建一个动态选择字段,但是它从不提交并且验证失败并出现以下错误.
I currently am creating a dynamic select field using WTFORMS, however it never submits and fails the validation with the following error.
Not a valid choice
我的字段是这样创建的:
My Field is created like this:
area = SelectField()
在视图中,我像这样从数据库中获取选项:
and in the view, i am grabbing the options from the db like so:
form = MytestForm()
form.area.choices = [(a.id, a.name) for a in Area.objects.all()]
但是,如果我创建静态选项,它会起作用.
It works however if i create static options.
推荐答案
我的猜测是 Area.id
是一个 int
- 当数据从客户端返回时WTForms 将其视为字符串,除非将可调用对象传递给 wtforms.fields.SelectField
构造函数:
My guess is that Area.id
is a int
- when data comes back from the client it is treated as a string by WTForms unless a callable is passed to the coerce
keyword argument of the wtforms.fields.SelectField
constructor:
area = SelectField(coerce=int)
或者,如果您使用 SQLAlchemy,您可以使用 wtforms.ext.sqlalchemy.fields.QuerySelectField
(wtforms_sqlalchemy
(如果您使用的是 WTForms 3+):
Alternately, if you are using SQLAlchemy you could use wtforms.ext.sqlalchemy.fields.QuerySelectField
(wtforms_sqlalchemy
if you are using WTForms 3+):
area = QuerySelectField(query_factory=Area.objects.all,
get_pk=lambda a: a.id,
get_label=lambda a: a.name)
这篇关于不是动态选择字段 WTFORMS 的有效选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!