Not a Valid Choice for Dynamic Select Field WTFORMS

a 夏天 提交于 2019-11-26 18:05:51

问题


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.


回答1:


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)



回答2:


Here is how you can solve it without 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)


来源:https://stackoverflow.com/questions/13964152/not-a-valid-choice-for-dynamic-select-field-wtforms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!