不是动态选择字段WTFORMS的有效选择 [英] Not a Valid Choice for Dynamic Select Field WTFORMS
问题描述
我现在正在创建一个使用WTFORMS的动态选择字段,但是它从不提交并且没有通过下面的错误验证。
不是有效的选择
我的字段是这样创建的:
area = SelectField()
和在视图中,我从数据库中抓取选项,如下所示:
form = MytestForm()
表单。 area.choices = [(a.id,a.name)for a Area.objects.all()]
$ b $如果我创建了静态选项,它可以工作。
我的猜测是 Area。当数据从客户端返回时,它被WTForms视为一个字符串,除非一个可调用的字符串是一个
关键字参数#wtforms.fields.SelectField> int
传递给 coerce wtfor ms.fields.SelectField
构造函数:
area = SelectField(coerce = int)
或者,如果您正在使用SQLAlchemy,则可以使用wtforms.ext.sqlalchemy.fields.QuerySelectField
( wtforms_sqlalchemy
如果您使用的是WTForms 3 +):
$ p $ c $ area $ QuerySelectField(query_factory = Area.objects.all
get_pk = lambda a:a.id,
get_label = lambda a:a.name)
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.
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)
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屋!