Reputation: 1329
<option value="1" {{ selected }}>1</option>
<option value="2" {{ selected }}>2</option>
<option value="3" {{ selected }}>3</option>
<option value="4" {{ selected }}>4</option>
I have a flask app with a handful of dropdown menus. I want to pass the selected value when a user submits the form so they see their previous selection on the next page.
Could someone provide a simple example of this? I just cant conceptualize how to accomplish this.
Thanks
Upvotes: 4
Views: 4230
Reputation: 5372
Python Flask view
@app.route('/form/')
def form():
# list of tuples representing select options
choices = [(str(x), str(x)) for x in range(1, 20)]
# test if value was passed in (e.g. GET method), default value is 1
selected = request.args.get('choice', '1')
# application 'state' variable with default value and test
state = {'choice': selected}
return render_template('view_form.html', choices=choices, state=state)
Within Jinja template:
{% for row in choices %}
<option value="{{ row[0] }}"{% if row[0] == state.choice %} selected{% endif %}>{{ row[1] }}</option>
{% endfor %}
Upvotes: 6