selectfield flask wtf

  1. Import necessary modules:

    • from flask import Flask, render_template, request
    • from flask_wtf import FlaskForm
    • from wtforms import SelectField
    • from wtforms.validators import DataRequired
  2. Create Flask application object:

    • app = Flask(__name__)
  3. Create a form class that extends FlaskForm:

    • class MyForm(FlaskForm):
  4. Define the choices for the SelectField:

    • choices = [('option1', 'Option 1'), ('option2', 'Option 2'), ('option3', 'Option 3')]
  5. Create an instance of SelectField and set its properties:

    • select_field = SelectField('Select an option', choices=choices, validators=[DataRequired()])
  6. Add the SelectField to the form:

    • my_form = MyForm()
  7. Render the form in a template:

    • render_template('form.html', form=my_form)
  8. Handle form submission in a route:

    • @app.route('/submit', methods=['POST'])
    • def submit():
    • if my_form.validate_on_submit():
    • selected_option = my_form.select_field.data
    • return f"You selected: {selected_option}"
  9. Run the Flask application:

    • if __name__ == '__main__':
    • app.run()

Note: The above steps outline the basic process of using Flask-WTF's SelectField to create a form with a select dropdown. It assumes that you have Flask and Flask-WTF installed in your project. Additionally, you may need to create a HTML template for rendering the form.