In this blog post, we’ll teach you how to create dynamic forms based on user input using Streamlit’s session state function.
Streamlit’s session state lets you share variables throughout a user’s session. We’ll use one such variable to track the app’s state, which changes when the user hits the submit button.
In this article, we’re going to develop an application that generates forms based on a numerical input. To start, we’ll set up the session state variable and initialize it to 0. Then, we’ll create a function that the submit button triggers to update this variable. This process forms the core of our dynamic form setup.
import streamlit as st st.title('Dynamic Forms') if 'stage' not in st.session_state: st.session_state.stage = 0 def set_stage(stage): st.session_state.stage = stage
Next, we need to create the first form that will take as input a number.
with st.form(key='my_form'): n_forms=st.number_input('Number of forms to create', 0, 10) submit_button = st.form_submit_button(label='Submit forms', on_click=set_stage, args=(1,))
Take a look at the submit button – we’re utilizing the set_stage
function here, adjusting the value to 1. Now comes the part where we determine if the value is greater than 0. That’s our cue that the submit button has been pressed and we should proceed to generate the forms.
For this task, we’ve chosen to employ a dictionary. It’s a handy method to store the fresh form variables, as shown below. In addition, we’ll introduce another submit button to advance the stage once more, this time to 2. This progression keeps the dynamic form-creation process flowing.
if st.session_state.stage > 0: forms_dict={} for i in range(0,n_forms): forms_dict[i]=st.text_input(str(i)) st.button('Submit', on_click=set_stage, args=(2,))
Lastly, we should verify whether the stage variable has been changed, signaling that it’s time to make use of the stored variables from the forms_dict
dictionary.
To display these variables, we’ll employ the st.write
function. As an extra step, we’ll introduce a button designed to reset the stage back to 0, ensuring a smooth restart if needed.
if st.session_state.stage > 1: for i in forms_dict: st.write(forms_dict[i]) st.button('Reset', on_click=set_stage, args=(0,))
Let’s assemble all the pieces:
import streamlit as st import re import pandas as pd import numpy as np st.title('Dynamic Forms') if 'stage' not in st.session_state: st.session_state.stage = 0 def set_stage(stage): st.session_state.stage = stage with st.form(key='my_form'): n_forms=st.number_input('Number of forms to create', 0, 10) submit_button = st.form_submit_button(label='Submit forms', on_click=set_stage, args=(1,)) if st.session_state.stage > 0: forms_dict={} for i in range(0,n_forms): forms_dict[i]=st.text_input(str(i)) st.button('Submit', on_click=set_stage, args=(2,)) if st.session_state.stage > 1: for i in forms_dict: st.write(forms_dict[i]) st.button('Reset', on_click=set_stage, args=(0,))