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

why do we need redirect() in flask?

In the flask basic,

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

I don't understand why we need redirect(). It seems like we just want to load the index page, why not just use render_template()?

There are many new concepts used in this lesson, could you explain more about why do we need them?

Thanks.

1 Answer

Hello Chen.

If I just think about this difference I would say that if you render_template('index.html') you get that template, but you are not redirected to the index page. If you use the redirect, after function completion, you move on to the page of the redirection. This is what I thought when dealing with those for the first time, let me know if clear or not because I can't really find better words to explain this concept.

Also, I have just googled it and I found this discussion: http://stackoverflow.com/questions/21668481/difference-between-render-template-and-redirect

It is about http status codes that you get in the 2 different cases, which may be important the particular project, you may want to have a quick read as it is just a few lines.

Maybe more reliable sources will want to confirm/correct/integrate this..

Vittorio

Many thanks for your help! I think I have a better understand now. By template, it is the html file containing some python variable or code, right? Because it is not "truly" html, we just call it template. So the different is: render_template() gives us this "template", rather than a real html page. redirect() drives us to the real html page, which is a rendered version of "template". Please correct me if I'm wrong.

Besides that, I'm still confused how to decide which to use when I want to jump to a page. In other word, when should I use render_template() and when should I use redirect()?

Hi Chen.

I think you get what I meant more or less, but the template definitely is real HTML.

If you want to go to a page (after the submission of a form for instance) you want to use redirect.

Render template actually brings in the template, so it is useful to create a page. If you already have the right page and only need to point to that page, redirect is your choice.

Vittorio

Your explanation is so clear. Thanks very much, Vittorio!