Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
604 views
in Technique[技术] by (71.8m points)

python - Not a Valid Choice for Dynamic Select Field 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...