Besides rendering templates from our routes, it can be important to move from one route to another. This is the role of the function redirect().

Consider the case where we create our form in one route, but after the form submission we want the user to end up in another route. While we can set the action attribute in the HTML <form> tag go to any path, redirect() is the best option to move from one route to another.


Using this function inside another route will simply send us to the URL we specify. In the case of a form submission, we can use redirect() after we have processed and saved our data inside our validate_on_submit() check.

Why don’t we just render a different template after processing our form data? There are many reasons for this, one being that each route comes with its own business logic prior to rendering its template. Rendering a template outside the initial route would mean you need to repeat some or all of this code.

Once again, to avoid possible URL string pitfalls, we can utilize url_for() within redirect(). This allows us to navigate routes by specifying the route function name instead of the URL path.

redirect(url_for("new_route", _external=True, _scheme='https'))
  • we must add two new keyword arguments to our call of url_for()
  • the keyword arguments _external=True and _scheme='https' ensure that the URL we redirect to is a secure HTTPS address and not an insecure HTTP address

Similarly, regular keyword arguments can be added if necessary.

redirect(url_for("new_route", new_var=this_var, _external=True, _scheme='https'))



Note the added flask imports: url_for and redirect. These will be used inside our route to change pages after the new recipe form submission.

In the index route of app.py add a return statement still within if recipe_form.validate_on_submit():. Start by returning the path string we want to go to using url_for(). Use the "recipe" route function as the main argument and set id to new_id as the keyword argument.

Make sure to set and include the _external and _scheme keyword arguments to load an HTTPS URL.

When submitting a recipe the browser should simply print the correct URL string for the added recipe.


Now that the URL string is set, let’s add redirect() to the return statement and use the set url_for() as the argument.

When complete, the form submission should change the page to the recipe that was just added. Good work!

Sign up to start coding

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?