selectfield flask wtf
Import necessary modules:
from flask import Flask, render_template, request
from flask_wtf import FlaskForm
from wtforms import SelectField
from wtforms.validators import DataRequired
Create Flask application object:
app = Flask(__name__)
Create a form class that extends FlaskForm:
class MyForm(FlaskForm):
Define the choices for the SelectField:
choices = [('option1', 'Option 1'), ('option2', 'Option 2'), ('option3', 'Option 3')]
Create an instance of SelectField and set its properties:
select_field = SelectField('Select an option', choices=choices, validators=[DataRequired()])
Add the SelectField to the form:
my_form = MyForm()
Render the form in a template:
render_template('form.html', form=my_form)
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}"
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.