Skip to content

Instantly share code, notes, and snippets.

@overdese
Last active June 15, 2021 06:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save overdese/abebc48e878662377988 to your computer and use it in GitHub Desktop.
Save overdese/abebc48e878662377988 to your computer and use it in GitHub Desktop.
WTF SelectField with dynamic choice

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().

From

@karlastone4
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment