class wtforms.fields.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.
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 coerce keyword arg to SelectField says that we use int() to coerce form data. The default coerce is unicode().
Great reference, but do you know how to save the items in a data base? When I have used something similar it would add the int to the database instead of the selection.