Michael
Michael

Reputation: 67

Sending a value from HTML dropdown to flask app.route

I would like to pass a value, from a dropdown box in HTML, to my route in flask. The selected value of the dropdown should be in the URL: 127.0.0.1:5000/switchselect/zone=be (or something simular)

@app.route('/switchselect/<zone>', methods= ['GET', 'POST'])
@login_required
def switchselect(zone):
    if request.method == 'POST':
        zone=request.form[zone]
        return "zone: " + zone
    else:
        return redirect(url_for('index'))

In HTML I have:


<div class="dropdown" style="padding-top:25px">
<button class="btn btn-default dropdown-toggle" type="button" id="menu1" data-toggle="dropdown">BE  <span class="caret"></span></button>
<ul class="dropdown-menu" role="menu" aria-labelledby="menu1">
<li role="presentation"><a role="menuitem" tabindex="-1" href="{{ url_for('switchselect')}}">Actual Config</a></li>
<li role="presentation"><a role="menuitem" tabindex="-1" href="#">Archive</a></li>
</ul>
</div>

I try to solve it this way because I want to make a template for the page /switchselect/, regardless of the zone.

So, how can I pass the value of the selected value in the dropdown to my route in flask?

Forgive me if I made any mistakes, I'm new in Python and Flask..

Upvotes: 2

Views: 1215

Answers (1)

Bitto
Bitto

Reputation: 8225

You can pass it from the url_for that you have used in the a tag

url_for('route_name', variable_name=variable_value)

In your template

<a role="menuitem" tabindex="-1" href="{{ url_for('switchselect', zone='be')}}">Actual Config</a>

Change the zone value to the value you want to pass.

When you are clicking on the link in the drop down the method is GET

@app.route('/switchselect/<zone>', methods= ['GET', 'POST'])
@login_required
def switchselect(zone):
        return "zone: " + zone 

This will give you a 404 if the zone variable is not present. You can give a default parameter and redirect to index.

@app.route('/switchselect/', defaults={'zone': None})
@app.route('/switchselect/<zone>', methods=['GET', 'POST'])
@login_required
def switchselect(zone):
    if zone:
        return "zone: " + zone
    return redirect(url_for('index'))

Upvotes: 3

Related Questions