Reputation: 31
If x=ohio
I want to redirect the user to /weather/ohio
All I have been able to get to work is /weather/?x=ohio
I am doing this so a second route @app.route("/weather/") will be run. I am not sure what I am missing. IS this the best way to load /weather/ohio, where ohio is a variable loaded from a form.
@app.route("/weather/", methods = ['POST', 'GET'])
def weather():
if request.method == 'POST':
x = request.form['search_location']
return redirect(url_for('weather', x=x))
#print (y)
else:
return render_template("weather.html")
If I take the x= out I get the error "TypeError: url_for() takes 1 positional argument but 2 were given"
Upvotes: 2
Views: 8828
Reputation: 1383
You need to have the second endpoint with a path variable and give url_for()
the name of the function associated with the endpoint:
@app.route("/weather", methods = ["POST", "GET"])
def weather():
if request.method == "POST":
x = request.form["search_location"]
return redirect(url_for("weather_location", x=x))
else:
return render_template("weather.html")
@app.route("/weather/<x>")
def weather_location(x):
return "It's always sunny in {}".format(x)
Take a look at this other question for maybe a bit more clarity.
Upvotes: 3
Reputation: 64
If i understand your question correctly, you want a dynamic route?
Have a look here https://www.tutorialspoint.com/flask/flask_variable_rules.htm
@app.route("/weather/<variable>", methods = ['POST', 'GET'])
Upvotes: 0
Reputation: 7206
It takes keyword arguments for the variables:
url_for('add', variable=x)
Upvotes: 2