Passing a variable to redirect url_for in flask

Viewed 6169

I was wondering if it is possible to pass a value through redirect(url_for()) with out it becoming a GET.

Basic example: I have a home function:

@app.route("/")
def home(msg=None):
    return render_template("home.html", mgs=msg)

how can I pass an message to the home function? In other words can I do this:

@app.route("/logout")
def logout():
    logout_user()
    return render_template('home.html', msg="logged out")

with redirect(url_for())?

this:

@app.route("/logout")
def logout():
    logout_user()
    return redirect(url_for('home', msg="logged out"))

just gives me the url with a get /?msg='logged out'.

I understand that url_for is generating an url based on the name of the function being passed to it. Can you pass a value to that function?

4 Answers

Another way to go is using sessions:

Dont forget to add it to your imports

from flask import Flask, ..., session

In logout definition store the message in the session:

@app.route("/logout")
def logout():
    logout_user()
    session['msg'] = "logged out"
    return redirect(url_for('home'))

In the home function

@app.route("/")
def home(msg=None):
    return render_template("home.html", msg=session['msg'])

In the home template just use it as a usual variable:

<p>Dear user, you have been {{ msg }} </p>

This way you avoid using get and Flask takes care of all

Did you try this?

msg="logged out"
return redirect(url_for('home'),code=307)

Code 307 is used as "POST"

Related