flask wtforms multiple select

# 1. Import necessary modules
from flask import Flask, render_template
from flask_wtf import FlaskForm
from wtforms import SelectMultipleField

# 2. Create a Flask application
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your_secret_key'

# 3. Create a WTForms class for the form
class MyForm(FlaskForm):
    # 4. Define a SelectMultipleField in the form
    choices = [('option1', 'Option 1'), ('option2', 'Option 2'), ('option3', 'Option 3')]
    selected_options = SelectMultipleField('Select Options', choices=choices)

# 5. Create a route to handle the form
@app.route('/', methods=['GET', 'POST'])
def index():
    # 6. Create an instance of the form
    form = MyForm()

    # 7. Check if the form is submitted and valid
    if form.validate_on_submit():
        # 8. Process the selected options
        selected_values = form.selected_options.data
        return f'Selected Options: {", ".join(selected_values)}'

    # 9. Render the template with the form
    return render_template('index.html', form=form)

# 10. Create a template (index.html) to render the form
# {% extends "base.html" %}
# {% block content %}
#   <h2>Select Options</h2>
#   <form method="post">
#     {{ form.hidden_tag() }}
#     {{ form.selected_options.label }}
#     {{ form.selected_options() }}
#     <input type="submit" value="Submit">
#   </form>
# {% endblock %}

# 11. Run the Flask application
if __name__ == '__main__':
    app.run(debug=True)