Creating Dynamic Forms With Streamlit: A Step-By-Step Guide

Billy Bonaros
3 min readAug 24, 2023

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 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…

--

--