Created
June 12, 2017 00:40
-
-
Save get-data-/b53567033d0e2f636c0c96d8df284802 to your computer and use it in GitHub Desktop.
Not a Valid Choice for Dynamic Select Field WTFORMS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
A great answer that is very clean | |
https://stackoverflow.com/questions/13964152/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()] | |
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment