Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect to a URL which contains a 'variable part' in Flask (Python)

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

like image 768
Sandeep Raju Prabhakar Avatar asked Apr 18 '13 11:04

Sandeep Raju Prabhakar


People also ask

How do you pass a variable in redirect?

Click Action > URL Redirect. Give your action an internal title (something that makes sense to you in the survey). Enter the link to the site in the URL field. Scroll to the Fields To Pass and select the question, hidden value, or URL Variables you would like to pass in the Question to Send dropdown.

How do I redirect a link in Flask?

Flask class has a redirect() function. When called, it returns a response object and redirects the user to another target location with specified status code. location parameter is the URL where response should be redirected. statuscode sent to browser's header, defaults to 302.

How do I make a button action redirect to another page in Flask?

If you want your form to submit to a different route you can simply do <form action="{{ url_for('app. login') }}"> . If you just want to put a link to the page use the <a> tag. If you want to process the request and then redirect, just use the redirect function provided by flask.

What is the difference between Render_template and redirect in Flask?

redirect returns a 302 header to the browser, with its Location header as the URL for the index function. render_template returns a 200, with the index. html template returned as the content at that URL.


1 Answers

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'))
like image 58
williamsbdev Avatar answered Oct 07 '22 19:10

williamsbdev