flask wtf SelectField, dynamic input and validation

戏子无情 提交于 2019-12-12 18:21:01

问题


First question: dynamic input into a SelectField (choices), in my Database (sqlite, with SqlAlchemy) I have a Table, and from this table I wont all entries in the choices from the SelectField. As the selected result I need the ID from the entry.

foo_id = SelectField('Label', choices=[Foo.query.all()])

Second question: If I put this into the SelectField:

foo_id = SelectField('Foo', choices=[(1, 'Foo 1'), (2, 'Foo 2')])

Every time:

Not a valid choice

What goes on with the validation?

Thanks for your time, have a nice day!


回答1:


Two answers:

  1. Use wtforms.ext.sqlalchemy.fields.QuerySelectField

  2. Add a callable coerce argument that will coerce the strings you get back from the browser:

    SelectField('Foo', coerce=int, choices=[(1, 'Foo 1'), (2, 'Foo 2')])
    


来源:https://stackoverflow.com/questions/17192595/flask-wtf-selectfield-dynamic-input-and-validation

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