11

I'm trying to redirect to a URL in Flask. The target URL that I'm trying to redirect to has a variable like this /dashboard/<username> which has a view as follows,

@app.route('/dashboard/<username>')
def dashboard(username):
    return render_template('dashboard.html', username=username)

How do I redirect to this URL using the Flask's redirect() & url_for() functions. I have tried this,

return redirect(url_for("index"))

which works fine as index is an URL without any variable part (/index) in my application. But, how do I do it for URLs which have variable paths?

Thanks

2 Answers 2

16

You will want to create your URL with url_for by giving it the name of your URL, the keyword arg, and value for your URL parameter in the following manner:

return redirect(url_for('dashboard', username='foo'))
Sign up to request clarification or add additional context in comments.

Comments

0

The point '.dashboard' is important

return redirect(url_for('.dashboard', username='foo'))

1 Comment

Your answer is the same as the accepted answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.