2018/8/4 16:43:40,作 者: 黄兵
SelectField(default field arguments, choices=, coerce=unicode, option_widget=None)
Select fields keep a choices property which is a sequence of (value, label) pairs. The value portion can be any type in theory, but as form data is sent by the browser as strings, you will need to provide a function which can coerce the string representation back to a comparable object.
Select fields with static choice values:
class PastebinEntry(Form): language = SelectField(u'Programming Language', choices=[('cpp', 'C++'), ('py', 'Python'), ('text', 'Plain Text')])
Note that the choices keyword is only evaluated once, so if you want to make a dynamic drop-down list, you’ll want to assign the choices list to the field after instantiation. Any inputted choices which are not in the given choices list will cause validation on the field to fail.
Select fields with dynamic choice values:
class UserDetails(Form): group_id = SelectField(u'Group', coerce=int) def edit_user(request, id): user = User.query.get(id) form = UserDetails(request.POST, obj=user) form.group_id.choices = [(g.id, g.name) for g in Group.query.order_by('name')]
Note we didn’t pass a choices to the
SelectField constructor, but rather created the list in the view function. Also, the coercekeyword arg to
SelectField says that we use
int() to coerce form data. The default coerce is
SelectField and its descendants are iterable, and iterating it will produce a list of fields each representing an option. The rendering of this can be further controlled by specifying option_widget=.