I’m building an application where I want to be able to save the input values in a json file, so I later can reload the values. I managed to get it to work with “session_state” and given the input values “key names”
See code below:
import streamlit as st
import json
def set_values_from_json():
file = st.session_state["file_uploader"]
if file:
if file.id != st.session_state["file_id"]:
json_dir = json.loads(file.read())
st.session_state["some_input"] = json_dir["some_value"]
st.session_state["some_other_input"] = json_dir["some_other_value"]
st.session_state["file_id"] = file.id
if "file_id" not in st.session_state:
st.session_state["file_id"] = -1
st.number_input(
"some_input",
key="some_input",
)
st.number_input(
"some_other_input",
key="some_other_input",
)
file = st.file_uploader(
"input json!", key="file_uploader", on_change=set_values_from_json
)
However, I keep getting a “The widget with key “some_input” was created with a default value but also had its value set via the Session State API.” warning the first time I load my json. Is there a way around this? Ether suppresses the warning or an alternative approach that doesn’t resolve in a warning?
Bonus question: The file_uploader “on_change” seems to trigger every time when it holds a file, not only when the file is changed. Is this a bug or intentional?
I also have this question, streamlit version 1.12.0, python 3.10.2 - on first upload it triggers a warning, but then never again unless streamlit itself is stopped and started. Any ideas - just suppressing the warning would be good enough for me
It’s not recommended to simultaneously set a widget’s default value and manipulate its key in Session State. Instead use only the key and initialize the value through Session State.
In your example, you’ve already established a default value of the widget with st.session_state['date_period'] = (min_date, max_date) and setting key='date_period' in the widget. You don’t need to also set value=(min_date, max_date) in the widget.
import streamlit as st
import polars as pl
radio_df = pl.DataFrame({
'radio': ['Comercial', 'Comercial', 'RFM'],
'day': pl.Series(['2024-01-01', '2024-07-15', '2024-12-14']).str.strptime(pl.Date, "%Y-%m-%d"),
'values': [1, 2, 3]
})
radio_options = ['Comercial', 'RFM']
# Sidebar Filters
with st.sidebar:
st.title(':gear: Page Settings')
min_date = radio_df['day'].min()
max_date = radio_df['day'].max()
if 'date_period' not in st.session_state:
st.session_state['date_period'] = (min_date, max_date)
# Date Filter
new_date_period = st.date_input(
label=':calendar: Select the time period',
min_value=min_date,
max_value=max_date,
key='date_period'
)