Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


Using WTForms for SelectField in Flask

I need to create a SelectField for my application but I'm confused on how to use it. The documentation don't say much. https://wtforms-components.readthedocs.org/en/latest/#selectfield

Could anyone please provide an example using the SelectField? Each time I try to do something I get more confused :(

UPDATE: I was looking in the wrong place: here is the documentation: http://wtforms.readthedocs.org/en/latest/fields.html

2 Answers

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

You add a SelectField just like you do any other but you have to provide it with choices. choices is a list of pairs, or tuples with two items in them. The first tuple member is the value that'll actually be submitted to your form and the second is the text that'll show to the end user. The example provided on the second link you included shows exactly how to create the field.

class PastebinEntry(Form):
    language = SelectField(
        'Programming Language',
        choices=[('cpp', 'C++'), ('py', 'Python'), ('text', 'Plain Text')]
Jacopo Scrinzi
Jacopo Scrinzi
16,668 Points

@Kenneth there is any way to dynamically change the choices? i want to have a select menu with the users name in a DB. right now if i add a new user to have it in the select menu i have to restart the flask app.

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

Check out the docs for the SelectField. There's a dynamic example that should get you at least part of the way there.