Categories
Python Answers

How to get value from select tag using Python Flask?

Spread the love

Sometimes, we want to get value from select tag using Python Flask.

In this article, we’ll look at how to get value from select tag using Python Flask.

How to get value from select tag using Python Flask?

To get value from select tag using Python Flask, we can use the request.form propety in our view.

For instance, we write

from flask import Flask, flash, redirect, render_template, \
     request, url_for

app = Flask(__name__)

@app.route('/')
def index():
    return render_template(
        'index.html',
        data=[{'name':'red'}, {'name':'green'}, {'name':'blue'}])

@app.route("/test" , methods=['GET', 'POST'])
def test():
    select = request.form.get('comp_select')
    return(str(select))

if __name__=='__main__':
    app.run(debug=True)

to use select = request.form.get('comp_select') in the test view to get the value of the select element with the name attribute set to comp_select.

In our index.html template, we add

<form method="POST" action="{{ url_for('test') }}">
  <select name="comp_select">
    {% for o in data %}
    <option value="{{ o.name }}">{{ o.name }}</option>
    {% endfor %}
  </select>

  <button type="submit" class="btn btn-default">Go</button>
</form>

to add a form with the select element with the name attribute set to comp_select.

The options are rendered from the data list.

Conclusion

To get value from select tag using Python Flask, we can use the request.form propety in our view.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *