Search code examples
pythonflasklogin-page

Display username in base.html in Flask


I want to add current username in base.html, but I can't understand how make it.

I have got username, which takes from MySQL database

#app/routes

@app.route('/auth', methods=['GET', 'POST'])
def auth():
    msg = ''
    if request.method == 'POST' and 'username' in request.form and 'password' in request.form:
        username = request.form['username']
        hash = request.form['password']
        salt = b'$2b$12$Mw/92Q0HkYKTR.0.ghNQs.'
        password = bytes(hash, encoding='utf-8')
        hash_1 = bcrypt.hashpw(password,salt)
        cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        cursor.execute('SELECT * FROM user WHERE username = % s AND password = % s', (username, hash_1,))
        account = cursor.fetchone()
        if account:
            session['loggedin'] = True
            session['id'] = account['id']
            session['username'] = account['username']
            msg = 'Logged in successfully !'
            return render_template('index.html', msg=msg)
        else:
            msg = 'Неверное имя пользователя/пароль !'
    return render_template('auth.html', msg=msg)

How can I take the username field and get it to the base.html, when user is Loggined in? I tryed to make it with using documentation, but it doesn`t work.

#base.html
      {% if g.username %}
          <li><span>{{ g.user['username'] }}</span>
          {% else %}
        <a class="p-2 text-dark" href="/auth">Авторизация</a>
          {% endif %}

Solution

  • I make it

    {% if session.loggedin %}
          <a class="p-2 text-dark" href="/auth">Привет,{{session.username}} </a>
          {% else %}
          <a class="p-2 text-dark" href="/auth">Авторизация</a>