Date input range - index error while selecting

I am running into an issue in one of my apps with a date input widget. For this app, the widget allows the user to input a date range which then controls a bar chart in the app.

One thing I have noticed is that when selecting the dates from the calendar the app re-runs upon selection of the first date (before the second date is selected) which causes an index error in my code every time. When the user selects the second date everything runs smoothly, but it is not the best user experience to get a full page error in the middle of selecting their desired date range.

Any tips on how to avoid app execution until a complete selection is made?



Attaching some screenshots to demonstrate the issue.

Hi @joe_loftus, welcome to the Streamlit community!

Depending on how your code is structured, you could do something to the effect of:


start_date, end_date = st.date_input(...)

if start_date and end_date:
    do_something()

That way, the code won’t run unless you have a start and end date.

Best,
Randy

Hi randy, thank you for your suggestion but I am facing the same problem and I can’t get your suggested solution to work.

I doubt it is even possible as the expected output from the 'st.date_input(…) statement in this example are 2 variables. Streamlit immediately throws an error when selecting β€˜start_date’ because the end_date variable is not defined yet. ie the error is generated even before getting to the if-statement. The same happens when

Perhaps I am mis-understanding you suggested solution, so maybe you could clarify on this?

Thanks!

Hello @ randyzwitch,

Above solution is no working. Please suggest something.

You just need to check the length of the tuple.

dates = st.date_input(label="Dates", value=())
if len(dates) != 2:
    st.stop()

start_date, end_date = dates
st.success(f"You selected {start_date} - {end_date}")

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.