Random generate + st.text_input + st.form: Unexpected behaviour

Hi,

I’ve been fighting with this simple issue for hours and would like some help, below is the code to a super-simple app that asks the user to input the random number generated above. I expected this code to create two-line .csv files that look like the following:

inputted_idx,idx
42,42

but instead, the number that will be saved under idx will be the next generated index (the one that will show after the refresh). for example:

inputted_idx,idx
42,22

What am I missing?
Thanks!

import random

import streamlit as st
import pandas as pd
import datetime

save_path = '~/'

idx = random.randint(1,100)
st.write(idx)

with st.form('Form', clear_on_submit=True):
    inputted_idx = st.text_input('Input the number written above')
    submit = st.form_submit_button('Submit')
    if submit:
        pd.DataFrame({
            'inputted_idx':[inputted_idx], 'idx':[idx]}) \
                      .to_csv(save_path+str(datetime.datetime.now().time()), index=False)