Not a Valid Choice for Dynamic Select Field WTFORMS

后端 未结 2 499
梦毁少年i
梦毁少年i 2020-12-02 14:26

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
         


        
2条回答
  •  清歌不尽
    2020-12-02 14:51

    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)
    

提交回复
热议问题