Checkbox State retention based on value in database column

In continuation to post available on below link.

Streamlit Checkbox - :balloon: Using Streamlit - Streamlit

I have four checkboxes, if 1st or 2nd or 1st and 2nd is checked in then 3rd and 4th should be disabled and if 3rd is checked then 1st,2nd and 4th should be disabled, if 4th is checked then 1st,2nd and 3rd should be disabled and this is working fine from the solution provided in above link.

but now if i have a condition i clicked the checked and its value got entered into database table column then when i reopen same page then i should have what i checked in earlier with other checkboxes disabled.

need help here!!

Thanks in advance streamlit community!!

Hey @Manish3,

Thanks for sharing your question. Please update your post to include a runnable code snippet that we can use to reproduce the issue you’re describing.

1 Like

Adding my code here where I want to add a condition if in SQL DB if i have value for checkbox (for example 4 then it should disable above three, this is similar to earlier condition i.e.
if 1st or 2nd or 1st and 2nd is checked in then 3rd and 4th should be disabled and if 3rd is checked then 1st,2nd and 4th should be disabled, if 4th is checked then 1st,2nd and 3rd should be disabled)

If i use directly the value from my DB and disable the checkbox then even if i uncheck it then state will not change of checkbox.

import streamlit as st
import pyodbc
import pandas as pd
from Az_Configuration_File import get_azure_connection_string

def disable_checkboxes():
## Dict with the disable conditions
disable = st.session_state.disable

## Current checkboxes' values
chk1, chk2, chk3, chk4 = (
    st.session_state.chk1,
    st.session_state.chk2,
    st.session_state.chk3,
    st.session_state.chk4,
)

## Logic to disable checkboxes
disable[1] = chk3 or chk4
disable[2] = chk3 or chk4
disable[3] = (chk1 and chk2) or chk4
disable[4] = (chk1 and chk2) or chk3

def main():

Uname = st.text_input('Username')
conn_str = get_azure_connection_string()
if not isinstance(conn_str, str):
    raise ValueError("Connection string is not a string")

conn = pyodbc.connect(conn_str)

SQL_query = pd.read_sql_query("SELECT * FROM [dbo].[CheckboxTable] where [dbo].[CheckboxTable].[Username]=?" ,conn, params=[Uname])
st.write(SQL_query)

if "disable" not in st.session_state:
    st.session_state.disable = {1: False, 2: False, 3: False, 4: False}

"**✔️ Disabling Checkboxes and Session State**"

disable = st.session_state.disable
checkbox1,checkbox2,checkbox3,checkbox4 = [None]*4


checkbox1i = st.checkbox("First", disabled=disable[1], on_change=disable_checkboxes, key="chk1")
if checkbox1i:
    checkbox1 = 'Yes'
checkbox2i = st.checkbox("Second", disabled=disable[2], on_change=disable_checkboxes, key="chk2")
if checkbox2i:
    checkbox2 = 'Yes'
checkbox3i = st.checkbox("Third", disabled=disable[3], on_change=disable_checkboxes, key="chk3")
if checkbox3i:
    checkbox3 = 'Yes'
checkbox4i = st.checkbox("Fourth", disabled=disable[4], on_change=disable_checkboxes, key="chk4")
if checkbox4i:
    checkbox4 = 'Yes'

#Username = 'Manish'
def write_to_database(conn_str, Username, checkbox1, checkbox2, checkbox3, checkbox4):
    try:
        conn = pyodbc.connect(conn_str)
        cursor = conn.cursor()

        insert_query = """
        INSERT INTO [dbo].[CheckboxTable](Username, checkbox1, checkbox2, checkbox3, checkbox4)
        VALUES (?, ?, ?, ?, ?)
        """
        
        cursor.execute(insert_query, Username, checkbox1, checkbox2, checkbox3, checkbox4)
        conn.commit()
        conn.close()
        st.success('Data Written to Database')
    except Exception as e:
        st.error(f'Error: {e}')
        
if st.button("Submit"):
    Username = Uname  # Use the username entered in the text input
    write_to_database(conn_str, Username, checkbox1, checkbox2, checkbox3, checkbox4)

if name == “main”:
main()


I got the solution for my above question and below is the answer

import streamlit as st

import pandas as pd

df = pd.read_csv(r’myfilepath’)

def disable_checkboxes():
## Dict with the disable conditions
disable = st.session_state.disable

## Current checkboxes' values
chk1, chk2, chk3, chk4 = (
    st.session_state.chk1,
    st.session_state.chk2,
    st.session_state.chk3,
    st.session_state.chk4,
)

## Logic to disable checkboxes
disable[1] = chk3 or chk4
disable[2] = chk3 or chk4
disable[3] = (chk1 and chk2) or chk4
disable[4] = (chk1 and chk2) or chk3

def main():

checkbox_columns = ['chk1', 'chk2', 'chk3', 'chk4']

# Create a new dataframe to store the modified values
modified_df = df.copy()

# Iterate over each row in the dataframe
for index, row in df.iterrows():
    for col in checkbox_columns:
        if row[col] == 'Yes':
            # Update this column to 'Yes' and all others to 'False' in the new dataframe
            modified_df.loc[index, col] = False
        else:
            modified_df.loc[index, col] = True
            
        for index, row in modified_df.iterrows():
            chk1 = (row['chk1'])
            chk2= (row['chk2'])
            chk3= (row['chk3'])
            chk4= (row['chk4'])
            
        true_columns = []   
        for col in modified_df.columns:
            if col.startswith('chk'):
            # Check if any value in the column is True
                if df[col].any():
                    # If True is found, add column name to the list
                    true_columns.append(col)
        for col_data in true_columns:
            print(col_data)
            
         
            
if chk4 is not None and ("disable" not in st.session_state):
    st.session_state.disable = {1: chk1, 2: chk2, 3: chk3, 4: chk4}

if "disable" not in st.session_state:
    st.session_state.disable = {1: False, 2: False, 3: False, 4: False}
    

"**✔️ Disabling Checkboxes and Session State**"

disable = st.session_state.disable
for index, row in df.iterrows():
    chk1 = (row['chk1'])
    chk2= (row['chk2'])
    chk3= (row['chk3'])
    chk4= (row['chk4'])
    
st.checkbox("First", disabled=disable[1], on_change=disable_checkboxes, key="chk1")
st.checkbox("Second", disabled=disable[2], on_change=disable_checkboxes, key="chk2")
st.checkbox("Third", disabled=disable[3], on_change=disable_checkboxes, key="chk3")
st.checkbox("Fourth", disabled=disable[4],value = chk4, on_change=disable_checkboxes, key="chk4")

if name == “main”:
main()

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.