Radio buttons and st.form to handle session state

Hi,

I have a piece of code that is trying to read a dataframe and display each row along with a radio button. When the user chooses a radio button it should display the details of another column called job_description. So the code displays the rows along with the radio buttons, but when the user clicks, it is stuck at index 0. Also when the submit button is clicked the page clears out. I have read the other posts about session states st.form and radio buttons, but none of those have helped in solving the issue.

Code Snippet

        if st.session_state.df.empty:
            st.session_state.df = df
        
        with st.form(key='job_selection_form'):
        # Radio buttons and row display
            options = [f"{row['title']} - {row['company_name']}" for _, row in st.session_state.df.iterrows()]
            selected_row_index = st.radio(
                "Choose one option :",
                options,
                key="radio_group",  
                index = st.session_state.selected_row_index,
            )
            logger.info("Selected option:", selected_row_index)
            st.write("selected_row_index after update:", st.session_state.selected_row_index)
            logger.info("Before submit_button")
            submit_button = st.form_submit_button(label='Submit')
            logger.info("After submit_button")

            if submit_button:
                if st.session_state.selected_row_index is not None:
                    selected_row = st.session_state.df.iloc[st.session_state.selected_row_index]
                    st.write(f"**Description:** {selected_row['job_description']}")
                else:
                    st.write("Please select a job to view details.")

Version
Python 3.9.2
streamlit==1.27.1

A beginning


import streamlit as st
import pandas as pd

# Sample DataFrame
data = {
    'title': ['Job 1', 'Job 2', 'Job 3'],
    'company_name': ['Company A', 'Company B', 'Company C'],
    'job_description': ['Description 1', 'Description 2', 'Description 3']
}
df = pd.DataFrame(data)

# Initialize session state variables
if 'selected_row_index' not in st.session_state:
    st.session_state.selected_row_index = 0

# Display rows and radio buttons within the form
with st.form(key='job_selection_form'):
    selected_row_index = st.radio(
        "Choose one option :",
        range(len(df)),  # Use range(len(df)) instead of options
        format_func=lambda i: f"{df.iloc[i]['title']} - {df.iloc[i]['company_name']}",
        index=st.session_state.selected_row_index
    )

    # Update session state with selected row index
    st.session_state.selected_row_index = selected_row_index

    # Add submit button to the form
    submit_button = st.form_submit_button(label='Submit')

# Display job description if form is submitted
if submit_button:
    selected_row = df.iloc[st.session_state.selected_row_index]
    st.write(f"**Description:** {selected_row['job_description']}")

Hi Oscar1,

Thanks for taking the time, to look at the code.
I had shared only a small part of my code, and I think the issue could be that I have two forms in my code. The behavior of code has not changed, and the page just clears out and job_description is not displayed.

Complete code

import streamlit as st
import pandas as pd

# Initialize selected_row_index if not present in session state
if 'selected_row_index' not in st.session_state:
    st.session_state.selected_row_index = 0

def any_none(*args):
    return any(arg is None for arg in args)

def are_all_not_none(*args):
    return all(arg is not None for arg in args)

def get_data(save_path, job_title, job_location):

    #PROCESS INPUT DATA

    return df.head()

with st.sidebar.form(key="user_input"):
    st.header("Settings")
    job_title = st.text_input("Job Title")
    job_location = st.text_input("Job Location")
    uploaded_cv = st.file_uploader(
                "Upload your CV",
                accept_multiple_files=False,
                type=["pdf"],
            )
    submitted = st.form_submit_button("Search and Analyze")

if any_none(job_title, job_location, uploaded_cv) and submitted:
    st.error("Fields cannot be empty")

if are_all_not_none(job_title, job_location, uploaded_cv) and submitted:
    with st.spinner("Searching jobs..."):
        save_path = save_file(uploaded_cv)
        df = get_data(save_path, job_title, job_location)
        with st.form(key='job_selection_form'):
            selected_row_index = st.radio(
                        "Choose one option :",
                        range(len(df)),  # Use range(len(df)) instead of options
                        format_func=lambda i: f"{df.iloc[i]['title']} - {df.iloc[i]['company_name']}",
                        index=st.session_state.selected_row_index
                    )

            # Update session state with selected row index
            st.session_state.selected_row_index = selected_row_index

            # Add submit button to the form
            submit_button = st.form_submit_button(label='Submit')

        # Display job description if form is submitted
        if submit_button:
            selected_row = df.iloc[st.session_state.selected_row_index]
            st.write(f"**Description:** {selected_row['job_description']}")