Takeshi Patterson
Takeshi Patterson

Reputation: 1277

How do I make this function redirect to a given html page?

I'm trying to write a simple script for an exercise I created using Flask, that calculates a tip amount from a meal value entered into a form.

The first function below (meal_total) takes the value entered in the html form and sends it to a second function (tip_calculator) which then processes the tip amount then rendering a new html (tip_amount.html), which displays how much tip must be paid.

The first bit works ok, but when the second function is called, I am not redirected to the new 'tip_amount.html. So how do I get the function to redirect to that html.

@app.route('/tip', methods = ['GET', 'POST'])
def meal_total():
    form = Tip()
    if form.validate_on_submit():
        meal = form.meal.data
        tip_calculator(meal)

    else:
        print "please enter your meal amount"
    return render_template('tip.html', 
        form = form)

@app.route('/tip-amount')
def tip_calculator(meal):
    tax = 0.2
    tip = 0.15
    meal_total = meal + meal * tax
    tip = meal_total * 0.15
    return render_template('tip_amount.html',
                           tip = tip)

NOTE: I tried using the redirect function as below instead of the render_template(), but it will not allow me to send the parameters (tip) that I need to be displayed int the tip_amount.html template.

@app.route('/tip-amount')
def tip_calculator(meal):
    tax = 0.2
    tip = 0.15
    meal_total = meal + meal * tax
    tip = meal_total * 0.15
    return redirect('/tip_amount')

Upvotes: 0

Views: 65

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121914

You are simply calling the tip_calculator() function without returning its response:

if form.validate_on_submit():
    meal = form.meal.data
    tip_calculator(meal)

Add a return there:

if form.validate_on_submit():
    meal = form.meal.data
    return tip_calculator(meal)

tip_calculator is merely a support function here; you don't need to register it as a route at all.

You can use redirection still, but then you'd usually pass along any parameters as query parameters in the URL; this is easily done with url_for(), any extra parameters are rendered as URL parameters:

from flask import url_for

if form.validate_on_submit():
    meal = form.meal.data
    return redirect(url_for('tip_calculator', meal=meal))

which'll redirect you to /tip-amount?meal=<meal> (with the meal value filled in).

Your tip_calculator route would then take that value from the request:

@app.route('/tip-amount')
def tip_calculator():
    meal = request.args.get('meal', type=int)
    if meal is None:
        # redirect back to form if the parameter is missing or not an integer
        return redirect(url_for('meal_total'))
    tax = 0.2
    tip = 0.15
    meal_total = meal + meal * tax
    tip = meal_total * 0.15
    return render_template('tip_amount.html', tip=tip)

Upvotes: 1

Related Questions