Python 不是动态选择字段 WTFORMS 的有效选择
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13964152/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Not a Valid Choice for Dynamic Select Field WTFORMS
提问by ismail
I currently am creating a dynamic select field using WTFORMS, however it never submits and fails the validation with the following error.
我目前正在使用 WTFORMS 创建一个动态选择字段,但是它从不提交并且验证失败并出现以下错误。
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.
但是,如果我创建静态选项,它会起作用。
采纳答案by Sean Vieira
My guess is that Area.idis a int- when data comes back from the client it is treated as a stringby WTForms unless a callable is passed to the coercekeyword argument of the wtforms.fields.SelectFieldconstructor:
我的猜测是,Area.id是int-当数据从它被视为一个客户端回来的字符串由WTForms除非调用传递给coerce了的关键字参数wtforms.fields.SelectField的构造函数:
area = SelectField(coerce=int)
Alternately, if you are using SQLAlchemy you could use wtforms.ext.sqlalchemy.fields.QuerySelectField(wtforms_sqlalchemyif you are using WTForms 3+):
或者,如果您使用的是 SQLAlchemy,则可以使用wtforms.ext.sqlalchemy.fields.QuerySelectField(wtforms_sqlalchemy如果您使用的是 WTForms 3+):
area = QuerySelectField(query_factory=Area.objects.all,
get_pk=lambda a: a.id,
get_label=lambda a: a.name)
回答by Rickard Zachrisson
Here is how you can solve it without QuerySelectField.
这是在没有 QuerySelectField 的情况下解决它的方法。
Here is how I did:
这是我的做法:
years = [(str(y), y) for y in reversed(range(1950, 2013))]
years.insert(0, ('','year'))
year = wt.SelectField(choices=years)

