l.z.lz
l.z.lz

Reputation: 393

How to redirect according to radio button value in Flask?

I'm very new to Flask and I would like to do the following:

  1. In my index.html there are two radio buttons and a submit button:
<form action="{{ url_for('click') }}" method="POST">    
    <div class="half">
        <input type="radio" name="option" value="a" />           
    </div>
    <div class="half">
        <input type="radio" name="option" value="b" />           
    </div>
        <input type="submit" value="Submit">
</form>
  1. When click submit button, the page should be redirect to another page according to selected radio button value, i.e. "a.html".

  2. I'm stuck with the python code here:

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

@app.route('/<selectedValue>', methods=['POST'])
def click():
    selectedValue = request.form['option']
    return redirect(url_for(selectedValue + '.html'))

Any suggestion would be appreciated!

Upvotes: 3

Views: 7426

Answers (1)

MrLeeh
MrLeeh

Reputation: 5589

Your code isn't working because when pressing the submit button you will send a post request to your target which is defined by the action attribute in your template. However the defined endpoint expects a selectedValue parameter which changes depending on your choice. The url_for() function you use in your template can't provide that because it is rendered to pure HTML when the template is sent to the client, meaning before a choice has been made.

Try a different approach:

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


app = Flask(__name__)


@app.route('/', methods=['GET', 'POST'])
def home():
    if request.method == 'POST':
        selectedValue = request.form['option']
        return redirect(url_for('click', selectedValue=selectedValue))
    return render_template('index.html')


@app.route('/<selectedValue>')
def click(selectedValue):
    return render_template(selectedValue)


if __name__ == '__main__':
    app.run(host='localhost', port=5000, debug=True)

This way you will send the POST request to your home endpoint and use the request object to get your option value. Then you will call a redirect function providing providing the selectedValue.

NOTE: I would recommend using a separate endpoint function for each template you're using.

Upvotes: 5

Related Questions