How to get a value using flask from a selected option in a drop down list

How to Get a Value Using Flask from a Selected Option in a Drop Down List

In order to get a value from a selected option in a drop down list using Flask, you can follow these steps:

  1. Create an HTML form with the drop down list and a submit button.
  2. Define a Flask route that renders this form.
  3. Handle the form submission in another Flask route.

Example:

HTML form:

    
<!-- index.html -->
<form action="/process_form" method="POST">
  <label for="dropdown">Select an option:</label>
  <select id="dropdown" name="option">
    <option value="option1">Option 1</option>
    <option value="option2">Option 2</option>
    <option value="option3">Option 3</option>
  </select>
  <button type="submit">Submit</button>
</form>
    
  

Flask routes:

    
from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/process_form', methods=['POST'])
def process_form():
    selected_option = request.form['option']
    return f"The selected option is: {selected_option}"
    
  

In the above example, we have an HTML form with a drop down list containing three options. When the form is submitted, it makes a POST request to the “/process_form” route. In this route, we access the selected option using `request.form[‘option’]`, where “option” is the name attribute of the drop down list. Finally, the selected option is returned as the response.

Leave a comment