简体   繁体   中英

How to pass arguments for return redirect(url()) in flask

I'm trying to update the profile in flask. Everything working fine but once its edited msg is not displaying in html page when i give {{ msg11 }}. I'm not getting how to pass the arguments so that the msg will be displayed in html page. I tried this approach but its not displaying in html page

@app.route("/updateProfile", methods=["GET", "POST"])
def updateProfile():
    if request.method == 'POST':
        email = request.form['email']
        firstName = request.form['firstName']
        lastName = request.form['lastName']
        with sqlite3.connect('database.db') as con:
                try:
                    cur = con.cursor()
                    cur.execute('UPDATE users SET firstName = ?, lastName = ? WHERE email = ?', (firstName, lastName))
                    con.commit()
                    msg11 = "Saved Successfully"
                except:
                    con.rollback()
                    msg11 = "Error occured"
        con.close()
        return redirect(url_for('editProfile', msg11=msg11))

Adding editprofile function. I have removed sql queries in this function

def editProfile():
    if 'email' not in session:
        return redirect(url_for('root'))
    loggedIn, firstName, noOfItems = getLoginDetails()

        profileData = cur.fetchone()
    conn.close()
    return render_template("editProfile.html", profileData=profileData, loggedIn=loggedIn, firstName=firstName, noOfItems=noOfItems)

When you provide keyword arguments to the url_for function, Flask automatically encodes your values into URI components and appends them to your request url.

Using your code as an example, doing this

msg11='Saved Successfully'
return redirect(url_for('editProfile', msg11=msg11))

Will yield this URL when passed to the editProfile route

/editProfile?msg11=Saved+Successfully

You can easily extract this value using Flask's built-in request object

from flask import request
# Inside of editProfile() route
msg11 = request.args.get('msg11', None)

That way, you can simply check if this value exists (calling get() is the same as the usual Python convention where a value of None will be returned if the value is not found) and pass it along to your HTML template.

Furthermore, using Jinja's functionality you can display the message only if it is not a None value by using something like this

{% if msg11 is not none %}
<h1>{{ msg11 }}</h1>
{% endif %}

A complete minimum example is outline below

app.py

from flask import Flask, render_template, redirect, url_for, request

app = Flask(__name__)

@app.route("/updateProfile", methods=["GET", "POST"])
def updateProfile():
    msg11 = "Saved Successfully"
    return redirect(url_for("editProfile", msg11=msg11))

@app.route("/editProfile")
def editProfile():
    msg11 = request.args.get("msg11")
    return render_template("editProfile.html", msg11=msg11)

if __name__ == "__main__":
    app.run()

templates/editProfile.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>editProfile</title>
</head>
<body>
    {% if msg11 is not none %}
    <h1>{{ msg11 }}</h1>
    {% else %}
    <h1>msg11 has a value of None</h1>
    {% endif %}
</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM