Edit df with AgGrid and send edited data to database

Hi,

I am trying to edit an exisiting dataframe and then writing it to a database. The dataframe gets sent to the database (editable_df), but without the edits.




def edit_data(editable_df, key):
      with st.expander(key):
              with st.form('edit'):
                  grid_return = AgGrid(editable_df, editable=True, theme ='streamlit')
                  new_df = grid_return['data']
                  st.form_submit_button('confirm', on_click=sent_to_db(new_df))

def sent_to_db(new_df):
    new_df.to_sql(name = 'table', con = conn, if_exists = 'replace')


Greatly appreciate the help!

Sample code to update sqlite db using pandas and aggrid.

import streamlit as st
import pandas as pd
from st_aggrid import AgGrid
from sqlalchemy import create_engine


sqlfn = 'mydb.sqlite'
table_name = 'users'
engine = create_engine(f'sqlite:///{sqlfn}', echo=False)


def add_data():
    """Add sample data to sql table."""
    df = pd.DataFrame({'name' : ['User 1', 'User 2', 'User 3'],
                       'role' : ['member', 'admin', 'moderator']})
    try:
        df.to_sql(table_name, con=engine, if_exists='fail')
    except ValueError:
        pass


def edit_data(editable_df, label):
    with st.expander(label):
        with st.form('edit'):
            grid_return = AgGrid(editable_df, editable=True, theme='streamlit')
            new_df = grid_return['data']
            st.form_submit_button('confirm', on_click=sent_to_db(new_df))


def sent_to_db(new_df):
    new_df.to_sql(name=table_name, con=engine, if_exists='replace')


def sql_to_df():
    df = pd.read_sql(table_name, con=engine)
    df = df.drop(['index'], axis=1)
    return df


def main():
    add_data()

    df = sql_to_df()
    st.dataframe(df)

    editable_df = df.copy()
    edit_data(editable_df, 'Edit')

    updated_df = sql_to_df()
    if not editable_df.equals(updated_df):
        st.experimental_rerun()


if __name__ == '__main__':
    main()