I'm a newbie user to use the Flask framework and I'm trying to implement a following problem.
I've the webpage for the users which serves two links:
<a href="{{ url_for('user', user_name=name, user_id=id) }}">Settings</a>
<a href="{{ url_for('user', user_name=name, user_id=id) }}">Details</a>
And in the py
file I want to implement following functionality - one route, but two behaviors depends on the user action:
@app.route("/<user_name>/<int:user_id>")
def user(user_name, user_id):
# if user click on the "Settings" link then:
# ...
# some code
# ...
return render_template('user_settings.html', ...)
# if user click on the "Details" link then:
# ...
# some code
# ...
return render_template('user_details.html', ...)
Or maybe something like this - the same route but two different def's:
# if user click on the "Settings" link then:
@app.route("/<user_name>/<int:user_id>")
def user_settings(user_name, user_id):
# ...
# some code
# ...
return render_template('user_settings.html', ...)
# if user click on the "Details" link then:
@app.route("/<user_name>/<int:user_id>")
def user_details(user_name, user_id):
# ...
# some code
# ...
return render_template('user_details.html', ...)
Please give me some tips because I do not know how to do that? Thanks in advance for your help! :-)
EDIT: @dim: asking why I want to have the same URL? Above question it's just an example for better understanding what I want. In fact, I've an output in a table with rows and columns. Something like to output in the Oracle Enterprise Manager:
As you see there are two links but they have the same Oracle RMAN ID (it's important because query to the database has the same WHERE
clause, for example: SELECT ... FROM ... WHERE SESSION_RECID = :parrent_id
). So:
In conclusion, I want to render two different templates depends on links with the same endpoint.
You can use URL query string parameters. Basically pass a query string parameter like <a href="{{ url_for('user', user_name=name, user_id=id, settings='true') }}">Settings</a>
which will result in <a href="/sammy/873?settings=true">Settings</a>
.
Inside the view, you can check for the existence of the settings
parameter and then serve the proper template.
@app.route("/<user_name>/<int:user_id>")
def user_details(user_name, user_id):
# ...
# some code
# ...
if request.args.get('settings'):
return render_template('user_settings.html', ...)
else:
return render_template('user_details.html', ...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With