Hi everyone!
I’m working on a Streamlit application where I need to select a row from a dataframe, display a dialog to enter additional data, and reset certain values each time a new row is selected. However, I’ve encountered some issues in handling this correctly.
Problem Description:
- Row Selection: I need users to select a row from a dataframe filtered by a date. Each time a new row is selected, certain values need to be reset.
- Value Resetting: I want to ensure that each time a new row is selected, the values in the data entry dialog are reset to their default values.
My Approach:
@st.experimental_dialog(f"Agregar Causas de rebuts (En vasos)", width="large")
def add_codigo_dialog(selected_idunique):
if 'df_param_display' not in st.session_state:
st.session_state.df_param_display = init_df_param_display()
# Resetear los valores de 'Vasos' cada vez que se abre el diálogo
st.session_state.df_param_display['Vasos'] = None
st.write(f"ID Producción: {selected_idunique}")
if selected_idunique is not None:
df_param_display = st.session_state.df_param_display.copy()
parametro = st.data_editor(df_param_display, hide_index=True, disabled=['Param_ID', "Categoria", "Cat_Tipo"])
if st.button("Insertar datos en WasteG1"):
engine = userwaste.get_database_engine()
invalid_rows = False
for index, row in parametro.iterrows():
try:
if row['Vasos'] != 0 and row['Vasos'] is not None:
param_id = int(row['Param_ID'])
vasos = int(row['Vasos'])
id_produccion = int(selected_idunique)
userwaste.insert_wasteg1(engine, param_id, vasos, id_produccion)
st.session_state.df_param_display = init_df_param_display()
except ValueError:
st.warning(f"El valor en la fila {index + 1} para 'Vasos' no es numérico: {row['Vasos']}")
invalid_rows = True
if not invalid_rows:
# Reset
st.session_state.selected_idunique = None
st.session_state.df_param_display = init_df_param_display()
st.rerun()
def init_df_param_display():
df_param = userwaste.display_ParamG1()
df_param = df_param.assign(Vasos=[None] * len(df_param))
return df_param[['Param_ID', 'Categoria', 'Cat_Tipo', 'Vasos']]
execution:
# Inicializar si no existe
if "causes" not in st.session_state:
st.session_state.causes= None
if "selected_idunique" not in st.session_state:
st.session_state.selected_idunique= None
def generate_causes(fecha_inicio):
if "df" not in st.session_state:
st.session_state.causes = userwaste.display_ProduccionG1()
# Filtrar el dataframe por la columna 'Fecha'
filtered_df = st.session_state.causes[st.session_state.causes["Fecha"] == fecha_inicio]
input_text = st.text_input("Filtrar:", key="_input")
filtered_df.reset_index(drop=True, inplace=True)
filtered_df['row_num'] = filtered_df.index
output_data = search_data(input_text, filtered_df)
event = st.dataframe(
output_data,
key="marche",
on_select="rerun",
selection_mode=["single-row"],
)
# Seleccionar la primera fila por defecto
if not event.selection:
event.selection = {"rows": [0], "columns": []}
selection = event.selection
if selection:
selected_rows = selection["rows"]
selected_cols = selection["columns"]
original_index = filtered_df.index[selected_rows]
selected_df = st.session_state.causes.loc[original_index]
if not selected_df.empty:
st.session_state.selected_idunique = selected_df['Id_produccion'].iloc[0]
st.session_state.df_param_display = init_df_param_display()
add_codigo_dialog(st.session_state.selected_idunique)
else:
st.warning("No se ha seleccionado ninguna fila")
return st.session_state.causes
generate_causes(fecha_inicio)
I need to ensure that each time a new row is selected, the values in df_param_display
are reset.
T
hanks for any help