4
            <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

1 Answer 1

6

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 %}
Sign up to request clarification or add additional context in comments.

3 Comments

I tried this and when I select any option, submit the form, the next page resets the selection to 1.
it works when changing this: selected = str((request.form['choz'])) #selected = request.args.get('choice', '1')
@abigperson I have a question on dropdown using Flask and python too. Mind helping me here: stackoverflow.com/questions/49628274/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.