Hello,
You may reproduce the behavior I describe by executing the application code below.
I made a form with two date inputs and a submit button. The ‘start’ and ‘end’ dates are auto-completed based on default values saved in a JSON file (or, if the file is not readable, the ‘start’ date will be 31 days before now, and the ‘end’ date will be today).
With the following code, I expect the application to display the default values when the page is first loaded, and when the page is reloaded after the user has submitted the form, the dates displayed should be the ones that the user has selected.
This works as expected when the following part is commented out, that is when the default values are never read from the file:
try:
with open('data_update_date.json') as f:
data = f.read()
saved_dates = json.loads(data)
startDate_default = datetime.datetime.strptime(saved_dates['startDate'], '%Y-%m-%d')
stopDate_default = datetime.datetime.strptime(saved_dates['stopDate'], '%Y-%m-%d')
# If the file doesn't exist or is corrupted, input default dates
except:
However, when the dates are read from the file, every other time the user submits the form, the dates selected by the user will not be considered when the page is reloaded (instead, the dates selected the previous time will be shown). One every other time, the result of the ‘print(startDate)’ will not be the date that the user has selected before last submitting the form, but the date that he had selected the previous time.
I can’t explain that behavior.
import datetime
import json
import streamlit as st
with st.form("dates"):
start, stop, update_button = st.columns((1, 1, 1))
# Read the dates from JSON file to autocomplete the input form
try:
with open('data_update_date.json') as f:
data = f.read()
saved_dates = json.loads(data)
startDate_default = datetime.datetime.strptime(saved_dates['startDate'], '%Y-%m-%d')
stopDate_default = datetime.datetime.strptime(saved_dates['stopDate'], '%Y-%m-%d')
# If the file doesn't exist or is corrupted, input default dates
except:
startDate_default = datetime.date.today() - datetime.timedelta(days=31)
stopDate_default = datetime.date.today()
# Start and end dates
startDate = start.date_input('Start Date', startDate_default)
stopDate = stop.date_input('End Date', stopDate_default)
print(startDate)
# Button to send the form
submitted = update_button.form_submit_button("Update data")
# When a user has submitted the form, update the JSON file with the selected dates so that the dates are displayed the next time the page is loaded
if submitted:
with open('data_update_date.json', 'w') as file:
file.write(json.dumps({'startDate': startDate,
'stopDate': stopDate}, default=str, indent=2))
The JSON file is as follows:
{
“startDate”: “2021-12-01”,
“stopDate”: “2021-12-22”
}