Skip to content

Instantly share code, notes, and snippets.

@juzten
Forked from overdese/dynamicFormWTF.md
Created June 15, 2021 06:26
Show Gist options
  • Save juzten/23110ffd17ca694a6f2d87ee954cc77e to your computer and use it in GitHub Desktop.
Save juzten/23110ffd17ca694a6f2d87ee954cc77e 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

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