Python Novice
Python Novice

Reputation: 2200

redirect while templating page

In Flask, how do you redirect to a different page while rendering a template?

@app.route('/foo.html', methods=['GET', 'POST'])
def foo():
    if request.method == "POST":
        x = request.form['x']
        y = request.form['y']
        if x > y:
            return redirect(render_template("bar.html", title="Bar"))
        else:
            return render_template("foo.html", title="Foo")

    return render_template("foo.html", title="Foo")


@app.route('/bar.html')
def bar():
    return render_template("bar.html", title="Bar")

return redirect(render_template("bar.html", title="Bar")) causes the full page that would be templated and displayed to instead appear in the URL:

http://localhost:5000/<!DOCTYPE html><html><head><title>Bar</title></head>...

This results in a 404 error because this page doesn't exist.

I've tried redirect(url_for('bar')) but I need to pass Jinja2 variables to url_for and have it template the page.

Upvotes: 0

Views: 3143

Answers (1)

Cfreak
Cfreak

Reputation: 19309

For redirecting you want a URL

return redirect(url_for('bar'))

You'll need to import url_for from Flask. If you need to pass additional variables you should put them in as parameters

somevalue = 1
return redirect(url_for('bar', somevar=somevalue) )

then

@app.route('/bar/<somevar>')
def bar(somevar):
    # do something with somevar probably
    return render_template("bar.html", title="Bar")

Upvotes: 2

Related Questions