Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask redirect url with anchor

Tags:

I have some problem with redirecting with anchors from python code.

My code:

func():
    ...
    redirect(url_for('my_view', param=param, _anchor='my_anchor'))

This redirect didn't redirect me to #my_anchor.

In template link like:

<a href="{{ url_for('my_view', param=param, _anchor='my_anchor') }}"></a>

works good... May be problem in flask function "redirect".

How I can use redirect with anchors in Flask?

Flask version 0.10.x

like image 498
astwild Avatar asked Feb 05 '14 16:02

astwild


2 Answers

if your goal is to be redirected to a page with an anchor preselected in the url I think the problem may be connected to the function you have passed in the 'url_for'. Below is my attempt to do what you described.

views.py

from flask import Flask
from flask import redirect, url_for
app = Flask(__name__)


@app.route('/')
def hello_world():
    return 'Hello World!'


@app.route('/myredirect')
def my_redirect():
    return redirect(url_for('hello_world',_anchor='my_anchor'))


if __name__ == '__main__':
    app.run()

This does not need a template, as as soon as you hit /myredirect you are redirected to / with anchor #my_anchor

After you get your views started with $ python views.py and navigate to http://127.0.0.1:5000/myredirect you end up on http://127.0.0.1:5000/#my_anchor

like image 167
ciacicode Avatar answered Oct 25 '22 12:10

ciacicode


A short and simple way of doing this is

return redirect(url_for('hello_world') + '#my_anchor')

instead of

return redirect(url_for('hello_world',_anchor='my_anchor'))

which works because url_for returns a string for the endpoint.

like image 33
Mark Kortink Avatar answered Oct 25 '22 12:10

Mark Kortink