Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Flask: redirect vs redirect(url_for)

I was trying to do a simple redirect(url_for('index')) but it doesn't work. The only way I can get away with it is by using only redirect('index').

Is there a new version to redirect or it's just my code that is wrong? Here is what I've done:

from flask import Flask, render_template, redirect, url_for

app = Flask(__name__)


@app.route("/")
@app.route("/index")
def hello():
       return render_template('index.html')

@app.route('/save', methods=['POST'])
def save():
      return redirect(url_for('index'))

 app.run(debug=True, port=8000, host='0.0.0.0')

1 Answer

Your index function is called hello I believe redirect(url_for("hello")) would work as you want because url_for expects the function name and creates the address, redirect just expects the address.

Goodluck! --Ricky

Thank you Ricky!

Glad to help. I check the docs for the function here.

Goodluck! --Ricky

The primary reason you may consider using url_for instead of just a regular redirect is that you may decide in the future to move your pages around ("home.htm" instead of "index.html" or something) but you're probably less likely to rename your functions.

This way if bits get jostled around and signup.html becomes register.html or join-us.htm, you'll still be able to use the url_for(signup) stuff without changing your code.

Gavin Ralston you are on the right track but this will not fix changes to file names. If the file name was changed he would have to change the render_template('index.html') function to render_template('home.html').

url_for is used for when the @app.route("/index") changes. It would prevent @app.route("/index") changed to @app.route("/home").

Goodluck! --Ricky

Ricky Catron

Right, that's what I was trying to say. :) You can decorate your function however you'd like, without changing the function name or the templates names you're using.

I was being ambiguous, though. The filenames changing definitely requires rendering a new template. Changing the url requires nothing more than changing a decorator. So "www.whatever.com/login" can become "www.whatever.com/register" or "www.whatever.com/lets-get-started" without changing your functions or filenames.