Login button needs 2x click

Hi, my login button here needs 2x click. On first time, when right credentials are entered, it does nothing.

The problem I’m facing is pertaining to the login button.
The issue is that when user logs in with right credential, then logs out, then logs in again.
In this second login, the user has to click the login button twice. Sometimes, this error also pops up in the first time when user is loggin in.

Thank you so much for helping in advance.

# Need to import pysqlite3 like this
__import__('pysqlite3')
import sys
sys.modules['sqlite3'] = sys.modules.pop('pysqlite3')

import streamlit as st

# Setting page config & header
st.set_page_config(page_title="Kristal Retriever", page_icon="πŸ“–", layout="wide", initial_sidebar_state="expanded")
st.header("πŸ“– Kristal Retriever")

from streamlit_extras.app_logo import add_logo
from st_pages import Page, Section, add_page_title, show_pages, hide_pages
from database_helper_functions import sign_up, fetch_users
import streamlit_authenticator as stauth
import bcrypt


# Add the logo to the sidebar
add_logo("https://assets-global.website-files.com/614a9edd8139f5def3897a73/61960dbb839ce5fefe853138_Kristal%20Logotype%20Primary.svg")

show_pages(
    [
        Page("main.py","Login", "πŸ—οΈ"),
        Page("pages/home.py", "About", "πŸ˜€"),
        Page("pages/bulk_upload_basic.py", "Bulk Upload - Basic", "πŸ“š"),
        Page("pages/bulk_upload_advanced.py", "Bulk Upload - Advanced", "πŸ“š"),
        Page("pages/qa_basic.py", "Q&A - Basic", "❓"),
        Page("pages/qa_advanced.py", "Q&A - Advanced", "❓")
    ]
)

# Session state variables
if "logged_out" not in st.session_state:
    st.session_state.logged_out = False

if "logged_in" not in st.session_state:
    st.session_state.logged_in = False

if not st.session_state.logged_in:
    hide_pages(["About", "Bulk Upload - Basic", "Bulk Upload - Advanced", "Q&A - Basic", "Q&A - Advanced"])

if st.session_state.logged_out:
    hide_pages(["About", "Bulk Upload - Basic", "Bulk Upload - Advanced", "Q&A - Basic", "Q&A - Advanced"])

if "username" not in st.session_state:
    st.session_state.username = ''

if "Authenticator" not in st.session_state:
    st.session_state.Authenticator = None

if "logout" not in st.session_state:
    st.session_state.logout = False


try:
    users = fetch_users()

    emails = []
    usernames = []
    passwords = []

    for user in users:
        emails.append(user['key'])
        usernames.append(user['username'])
        passwords.append(user['password'])

    credentials = {'usernames': {}}
    
    for index in range(len(emails)):
        credentials['usernames'][usernames[index]] = {'name': emails[index], 'password': passwords[index]}

    Authenticator = stauth.Authenticate(credentials, cookie_name = 'Streamlit', key = 'abcdef', cookie_expiry_days = 0)
    st.session_state.Authenticator = Authenticator

    # email, authentication_status, username = Authenticator.login('Login', 'main')

    
    with st.form(key='login'):
        st.subheader('Login')

        username = st.text_input('Username', placeholder='Enter Your Username', help =
                        '''
                        Please make sure:
                        1) Username is at least 2 characters long
                        2) Username contains only alphanumeric characters (letters and digits)
                        '''
                        )
        
        password = st.text_input('Password', placeholder='Enter Your Password', type='password',
                            help =
                            '''
                            Please make sure:
                            1) Length of password is at least 6 characters long
                            2) Password can contain any characters (letters, digits, underscore, dashes, period etc)
                            '''
                            )
        
        btn1, bt2, btn3, btn4, btn5 = st.columns(5)

        with btn1:
            login_button = st.form_submit_button('Login')


    # Checking if login button is pressed
    if login_button:
        
        info, info1 = st.columns(2)
        
        if username:
            if username in usernames:
                if password:

                    st.session_state.username = username
                    password_match = bcrypt.checkpw(password.encode(), credentials['usernames'][username]['password'].encode())

                    if password_match is True:
                        st.session_state.logged_in = True
                        st.session_state.logout = False

                        st.sidebar.subheader(f'Welcome {username}')
                        logout_button = Authenticator.logout('Log Out', 'sidebar')

                        if logout_button:
                            st.session_state.logged_out = True
                            st.session_state.logged_in = False

                    elif password_match is False:
                        with info:
                            st.error('Incorrect Password or username')

                else:
                    with info:
                        st.warning('Please enter the password field')

            else:
                with info:
                    st.warning('Username does not exist in database')

        else:
            with info:
                st.warning('Please enter the username field')

except:
    st.success('Refresh Page')

I’m getting this error in streamlit console:

[09:37:53] πŸ”„ Updated app!

2023-11-08 09:37:58.730 Uncaught app exception

Traceback (most recent call last):

  File "/home/adminuser/venv/lib/python3.11/site-packages/streamlit/runtime/state/session_state_proxy.py", line 119, in __getattr__

    return self[key]

           ~~~~^^^^^

  File "/home/adminuser/venv/lib/python3.11/site-packages/streamlit/runtime/state/session_state_proxy.py", line 90, in __getitem__

    return get_session_state()[key]

           ~~~~~~~~~~~~~~~~~~~^^^^^

  File "/home/adminuser/venv/lib/python3.11/site-packages/streamlit/runtime/state/safe_session_state.py", line 111, in __getitem__

    raise KeyError(key)

KeyError: 'logged_in'


During handling of the above exception, another exception occurred:


Traceback (most recent call last):

  File "/home/adminuser/venv/lib/python3.11/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 541, in _run_script

    exec(code, module.__dict__)

  File "/mount/src/kristalgptv2/main.py", line 40, in <module>

    if not st.session_state.logged_in:

           ^^^^^^^^^^^^^^^^^^^^^^^^^^

  File "/home/adminuser/venv/lib/python3.11/site-packages/streamlit/runtime/state/session_state_proxy.py", line 121, in __getattr__

    raise AttributeError(_missing_attr_error_message(key))

AttributeError: st.session_state has no attribute "logged_in". Did you forget to initialize it? More info: https://docs.streamlit.io/library/advanced-features/session-state#initialization

2023-11-08 09:41:29.813 Uncaught app exception

Traceback (most recent call last):

  File "/home/adminuser/venv/lib/python3.11/site-packages/streamlit/runtime/state/session_state_proxy.py", line 119, in __getattr__

    return self[key]

           ~~~~^^^^^

  File "/home/adminuser/venv/lib/python3.11/site-packages/streamlit/runtime/state/session_state_proxy.py", line 90, in __getitem__

    return get_session_state()[key]

           ~~~~~~~~~~~~~~~~~~~^^^^^

  File "/home/adminuser/venv/lib/python3.11/site-packages/streamlit/runtime/state/safe_session_state.py", line 111, in __getitem__

    raise KeyError(key)

KeyError: 'logged_in'


During handling of the above exception, another exception occurred:


Traceback (most recent call last):

  File "/home/adminuser/venv/lib/python3.11/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 541, in _run_script

    exec(code, module.__dict__)

  File "/mount/src/kristalgptv2/main.py", line 40, in <module>

    if not st.session_state.logged_in:

           ^^^^^^^^^^^^^^^^^^^^^^^^^^

  File "/home/adminuser/venv/lib/python3.11/site-packages/streamlit/runtime/state/session_state_proxy.py", line 121, in __getattr__

    raise AttributeError(_missing_attr_error_message(key))

AttributeError: st.session_state has no attribute "logged_in". Did you forget to initialize it? More info: https://docs.streamlit.io/library/advanced-features/session-state#initialization

2023-11-08 09:42:05.883 Uncaught app exception

Traceback (most recent call last):

  File "/home/adminuser/venv/lib/python3.11/site-packages/streamlit/runtime/state/session_state_proxy.py", line 119, in __getattr__

    return self[key]

           ~~~~^^^^^

  File "/home/adminuser/venv/lib/python3.11/site-packages/streamlit/runtime/state/session_state_proxy.py", line 90, in __getitem__

    return get_session_state()[key]

           ~~~~~~~~~~~~~~~~~~~^^^^^

  File "/home/adminuser/venv/lib/python3.11/site-packages/streamlit/runtime/state/safe_session_state.py", line 111, in __getitem__

    raise KeyError(key)

KeyError: 'logged_in'


During handling of the above exception, another exception occurred:


Traceback (most recent call last):

  File "/home/adminuser/venv/lib/python3.11/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 541, in _run_script

    exec(code, module.__dict__)

  File "/mount/src/kristalgptv2/main.py", line 40, in <module>

    if not st.session_state.logged_in:

           ^^^^^^^^^^^^^^^^^^^^^^^^^^

  File "/home/adminuser/venv/lib/python3.11/site-packages/streamlit/runtime/state/session_state_proxy.py", line 121, in __getattr__

    raise AttributeError(_missing_attr_error_message(key))

AttributeError: st.session_state has no attribute "logged_in". Did you forget to initialize it? More info: https://docs.streamlit.io/library/advanced-features/session-state#initialization

2023-11-08 09:42:33.230 Uncaught app exception

Traceback (most recent call last):

  File "/home/adminuser/venv/lib/python3.11/site-packages/streamlit/runtime/state/session_state_proxy.py", line 119, in __getattr__

    return self[key]

           ~~~~^^^^^

  File "/home/adminuser/venv/lib/python3.11/site-packages/streamlit/runtime/state/session_state_proxy.py", line 90, in __getitem__

    return get_session_state()[key]

           ~~~~~~~~~~~~~~~~~~~^^^^^

  File "/home/adminuser/venv/lib/python3.11/site-packages/streamlit/runtime/state/safe_session_state.py", line 111, in __getitem__

    raise KeyError(key)

KeyError: 'logged_in'


During handling of the above exception, another exception occurred:


Traceback (most recent call last):

  File "/home/adminuser/venv/lib/python3.11/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 541, in _run_script

    exec(code, module.__dict__)

  File "/mount/src/kristalgptv2/main.py", line 40, in <module>

    if not st.session_state.logged_in:

           ^^^^^^^^^^^^^^^^^^^^^^^^^^

  File "/home/adminuser/venv/lib/python3.11/site-packages/streamlit/runtime/state/session_state_proxy.py", line 121, in __getattr__

    raise AttributeError(_missing_attr_error_message(key))

AttributeError: st.session_state has no attribute "logged_in". Did you forget to initialize it? More info: https://docs.streamlit.io/library/advanced-features/session-state#initialization

2023-11-08 09:42:33.557 Uncaught app exception

Traceback (most recent call last):

  File "/home/adminuser/venv/lib/python3.11/site-packages/streamlit/runtime/state/session_state_proxy.py", line 119, in __getattr__

    return self[key]

           ~~~~^^^^^

  File "/home/adminuser/venv/lib/python3.11/site-packages/streamlit/runtime/state/session_state_proxy.py", line 90, in __getitem__

    return get_session_state()[key]

           ~~~~~~~~~~~~~~~~~~~^^^^^

  File "/home/adminuser/venv/lib/python3.11/site-packages/streamlit/runtime/state/safe_session_state.py", line 111, in __getitem__

    raise KeyError(key)

KeyError: 'logged_in'


During handling of the above exception, another exception occurred:


Traceback (most recent call last):

  File "/home/adminuser/venv/lib/python3.11/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 541, in _run_script

    exec(code, module.__dict__)

  File "/mount/src/kristalgptv2/main.py", line 40, in <module>

    if not st.session_state.logged_in:

           ^^^^^^^^^^^^^^^^^^^^^^^^^^

  File "/home/adminuser/venv/lib/python3.11/site-packages/streamlit/runtime/state/session_state_proxy.py", line 121, in __getattr__

    raise AttributeError(_missing_attr_error_message(key))

AttributeError: st.session_state has no attribute "logged_in". Did you forget to initialize it? More info: https://docs.streamlit.io/library/advanced-features/session-state#initialization

2023-11-08 09:42:34.777 Uncaught app exception

Traceback (most recent call last):

  File "/home/adminuser/venv/lib/python3.11/site-packages/streamlit/runtime/state/session_state_proxy.py", line 119, in __getattr__

    return self[key]

           ~~~~^^^^^

  File "/home/adminuser/venv/lib/python3.11/site-packages/streamlit/runtime/state/session_state_proxy.py", line 90, in __getitem__

    return get_session_state()[key]

           ~~~~~~~~~~~~~~~~~~~^^^^^

  File "/home/adminuser/venv/lib/python3.11/site-packages/streamlit/runtime/state/safe_session_state.py", line 111, in __getitem__

    raise KeyError(key)

KeyError: 'logged_in'


During handling of the above exception, another exception occurred:


Traceback (most recent call last):

  File "/home/adminuser/venv/lib/python3.11/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 541, in _run_script

    exec(code, module.__dict__)

  File "/mount/src/kristalgptv2/main.py", line 40, in <module>

    if not st.session_state.logged_in:

           ^^^^^^^^^^^^^^^^^^^^^^^^^^

  File "/home/adminuser/venv/lib/python3.11/site-packages/streamlit/runtime/state/session_state_proxy.py", line 121, in __getattr__

    raise AttributeError(_missing_attr_error_message(key))

AttributeError: st.session_state has no attribute "logged_in". Did you forget to initialize it? More info: https://docs.streamlit.io/library/advanced-features/session-state#initialization

tagging some people I’ve seen that helped a lot on this forum, thanks in advance: @Caroline @Franky1 @Charly_Wargnier @snehankekre

Hi @Yash_Mehta ,

I would try moving all the login logic from the if login to a callback function using the on_click= attribute in the st.button widget.

1 Like

Please refrain from tagging Streamlit staff in your posts in the future (check out our full guidelines on posting in the forum here). Thanks!

1 Like

Hi @CarlosSerrano Thanks for your response. I have modified the code as follows and it still does not work (Need to click twice on login button, but at least error messages in console are gone):

# Need to import pysqlite3 like this
__import__('pysqlite3')
import sys
sys.modules['sqlite3'] = sys.modules.pop('pysqlite3')

import streamlit as st

# Setting page config & header
st.set_page_config(page_title="Kristal Retriever", page_icon="πŸ“–", layout="wide", initial_sidebar_state="expanded")
st.header("πŸ“– Kristal Retriever")

from streamlit_extras.app_logo import add_logo
from st_pages import Page, Section, add_page_title, show_pages, hide_pages
from database_helper_functions import sign_up, fetch_users
import streamlit_authenticator as stauth
import bcrypt


# Add the logo to the sidebar
add_logo("https://assets-global.website-files.com/614a9edd8139f5def3897a73/61960dbb839ce5fefe853138_Kristal%20Logotype%20Primary.svg")

show_pages(
    [
        Page("main.py","Login", "πŸ—οΈ"),
        Page("pages/home.py", "About", "πŸ˜€"),
        Page("pages/bulk_upload_basic.py", "Bulk Upload - Basic", "πŸ“š"),
        Page("pages/bulk_upload_advanced.py", "Bulk Upload - Advanced", "πŸ“š"),
        Page("pages/qa_basic.py", "Q&A - Basic", "❓"),
        Page("pages/qa_advanced.py", "Q&A - Advanced", "❓")
    ]
)

# Session state variables
if "logged_out" not in st.session_state:
    st.session_state['logged_out'] = False

if "logged_in" not in st.session_state:
    st.session_state['logged_in'] = False

if not st.session_state.logged_in:
    hide_pages(["About", "Bulk Upload - Basic", "Bulk Upload - Advanced", "Q&A - Basic", "Q&A - Advanced"])

if st.session_state.logged_out:
    hide_pages(["About", "Bulk Upload - Basic", "Bulk Upload - Advanced", "Q&A - Basic", "Q&A - Advanced"])

if "username" not in st.session_state:
    st.session_state['username'] = ''

if "Authenticator" not in st.session_state:
    st.session_state['Authenticator'] = None

if "logout" not in st.session_state:
    st.session_state['logout'] = False

# Function defining what happens if login button is pressed
def login_button_pressed():
    
    info, info1 = st.columns(2)
    
    if username:
        if username in usernames:
            if password:

                st.session_state.username = username
                password_match = bcrypt.checkpw(password.encode(), credentials['usernames'][username]['password'].encode())

                if password_match is True:
                    st.session_state.logged_in = True
                    st.session_state.logout = False

                    st.sidebar.subheader(f'Welcome {username}')
                    logout_button = Authenticator.logout('Log Out', 'sidebar')

                    if logout_button:
                        st.session_state.logged_out = True
                        st.session_state.logged_in = False

                elif password_match is False:
                    with info:
                        st.error('Incorrect Password or username')

                else:
                    with info:
                        st.error('Please feed in your credentials properly')

            else:
                with info:
                    st.warning('Please enter the password field')

        else:
            with info:
                st.warning('Username does not exist in database')

    else:
        with info:
            st.warning('Please enter the username field')

try:
    users = fetch_users()

    emails = []
    usernames = []
    passwords = []

    for user in users:
        emails.append(user['key'])
        usernames.append(user['username'])
        passwords.append(user['password'])

    credentials = {'usernames': {}}
    
    for index in range(len(emails)):
        credentials['usernames'][usernames[index]] = {'name': emails[index], 'password': passwords[index]}

    Authenticator = stauth.Authenticate(credentials, cookie_name = 'Streamlit', key = 'abcdef', cookie_expiry_days = 0)
    st.session_state.Authenticator = Authenticator

    # email, authentication_status, username = Authenticator.login('Login', 'main')

    
    with st.form(key='login'):
        st.subheader('Login')

        username = st.text_input('Username', placeholder='Enter Your Username', help =
                        '''
                        Please make sure:
                        1) Username is at least 2 characters long
                        2) Username contains only alphanumeric characters (letters and digits)
                        '''
                        )
        
        password = st.text_input('Password', placeholder='Enter Your Password', type='password',
                            help =
                            '''
                            Please make sure:
                            1) Length of password is at least 6 characters long
                            2) Password can contain any characters (letters, digits, underscore, dashes, period etc)
                            '''
                            )
        
        btn1, bt2, btn3, btn4, btn5 = st.columns(5)

        with btn1:
            login_button = st.form_submit_button('Login', on_click = login_button_pressed)


except Exception as e:
    st.error(f'An error occurred: {e}')
    # st.success('Refresh Page')

And @Caroline, apologies didn’t read the guidlines. Will take care!

You can refer to my repo here: https://github.com/yashmehtakristal/KristalGPTv2/blob/main/main.py

I’ve searched a lot on streamlit and stackoverflow. Seems like a simple issue but idk where I am going wrong.