0

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 %}
3
  • Have you tried this approach: stackoverflow.com/questions/24922831/… ?
    – Bruck1701
    Commented Oct 20, 2020 at 7:03
  • Yes, but I don`t understand how I can use it in my code.
    – Dess
    Commented Oct 20, 2020 at 7:07
  • 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>
    – Dess
    Commented Oct 20, 2020 at 7:30

1 Answer 1

1

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>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.