Reputation: 393
I'm very new to Flask and I would like to do the following:
<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>
When click submit button, the page should be redirect to another page according to selected radio button value, i.e. "a.html".
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
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