Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.


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.