-1

How do you pass a value to a route while rendering a template in Flask?

@ui.route('/login', methods=['GET' , 'POST'])
def login():
    
    usr = User.query.filter_by(username=username).first()
    if request.method == "POST":
        ## login code
        username = request.form.get('username')
        if not check_password_hash(user.password, password):
            flash('Wrong creds')

            return render_template('login.html')
        else:
            return render_template('profile.html', usrname=username) 
        return render_template('login.html')
       

The goal is to pass the username of the User object to the PROFILE route so that the user sees his profile

@ui.route('/PROFILE/<usrname>', methods=['GET','POST'])

def PROFILE(usrname):

    usr = User.query.filter_by(username=usrname).first()
    if request.method == "POST":
        TEXT =request.form.get('text')
        usr.text = TEXT
        db.session.add(usr)
        db.session.commit()
    else:
        render_template('add_text.html')

2 Answers2

1

Re-direct internal route using url_for

Pseudo Code

from flask import Flask, redirect, url_for
.
.
.
@ui.route('/login', methods=['GET' , 'POST'])
def login():

    usr = User.query.filter_by(username=username).first()
    if request.method == "POST":
        ## login code
        username = request.form.get('username')
        if not check_password_hash(user.password, password):
            flash('Wrong creds')

            return render_template('login.html')
        else:
            redirect(url_for(f'/PROFILE/{username}') 
        return render_template('login.html')
Abdul Basit
  • 953
  • 13
  • 14
1

you could use redirect and url_for

@ui.route('/login', methods=['GET' , 'POST'])
def login():
    
    usr = User.query.filter_by(username=username).first()
    if request.method == "POST":
        ## login code
        username = request.form.get('username')
        if not check_password_hash(user.password, password):
            flash('Wrong creds')

            return render_template('login.html')
        else:
            return redirect(url_for('.PROFILE', usrname=username))
            # here url_for takes the function name 
        return render_template('login.html')