How do I populate a Dash datatable and append a csv from user input?

I appreciate the patience in advance. I am new to asking question in a forum like this!

The problem: I would like to get user input to populate a data table with derived values and then be able to append an existing csv with those values.

The code below gets me added rows to the data table, and rows + incorrect columns and values are added to the csv.

I hope someone could take a look and see where I am going wrong.

Thanks for the help. I hope this is enough simple info to help you help me.

import dash
from dash.dependencies import Input, Output, State
from dash import dash_table
from dash import dcc, html
import datetime as dt

import pandas as pd
import plotly.express as px

currentdatetime = dt.datetime.now()

app = dash.Dash(__name__,suppress_callback_exceptions=True)

df_columns =[{'name': 'Datetime', 'id': 'input1', 'type':'datetime'},
            {'name': 'input1', 'id': 'input1', 'type':'numeric'},
            {'name': 'input2', 'id': 'input2', 'type':'numeric'},
            {'name': 'derived1', 'id': 'derived1', 'type':'numeric'}],

app.layout = html.Div([
    html.Div([
        dcc.Input(
            id='input1',
            placeholder='Input 1',
            type='number',
            value='',
            style={'padding': 10}
        ),
        dcc.Input(
            id='input2',
            placeholder='Input 2',
            type='number',
            value='',
            style={'padding': 10}
        ),
        html.Button('add Data', id='adding-data', n_clicks=0)
    ], style={'height': 50}),

    dash_table.DataTable(
        id='our-table',
    ),

    html.Button('Export to Excel', id='save_to_csv', n_clicks=0),

    # Create notification when saving to excel
    html.Div(id='placeholder', children=[]),
    dcc.Store(id="store", data=0),
    dcc.Interval(id='interval', interval=1000),

])
# ------------------------------------------------------------------------------------------------


@app.callback(
    Output('our-table', 'data'),
    [Input('adding-data', 'n_clicks')],
    [State('input1', 'value'),
     State('input2', 'value')],
)
def add_rows(n_clicks,value,value2):
    dict =  {'Datetime':'', 
            'input1':value, 
            'input2':value2, 
            'derived1':value + value2
            }
    df = pd.DataFrame(dict, index=['Datetime'])
    df['Datetime'] = currentdatetime.strftime('%Y-%m-%d %H%M')
    data = df.to_dict('records')
    if n_clicks > 0:
        data = df.to_dict('records')
    return data




@app.callback(
    [Output('placeholder', 'children'),
     Output("store", "data")],
    [Input('save_to_csv', 'n_clicks'),
     Input("interval", "n_intervals")],
    [State('our-table', 'data'),
     State('store', 'data')]
)
def df_to_csv(n_clicks, n_intervals, dataset, s):
    output = html.Plaintext("The data has been saved to your folder.",
                            style={'color': 'green', 'font-weight': 'bold', 'font-size': 'large'})
    no_output = html.Plaintext("", style={'margin': "0px"})

    input_triggered = dash.callback_context.triggered[0]["prop_id"].split(".")[0]

    if input_triggered == "save_to_csv":
        s = 6
        df = pd.DataFrame(dataset, index=['index'])
        df.to_csv("assets/Data.csv", index=False, mode='a', header=False)
        return output, s
    elif input_triggered == 'interval' and s > 0:
        s = s-1
        if s > 0:
            return output, s
        else:
            return no_output, s
    elif s == 0:
        return no_output, s


if __name__ == '__main__':
    app.run_server(debug=True)

Additional info:

My end goal is to incorporate this code into my multipage app. I intend on utilizing postgresql for a login/ user data table as well as a table for the data received from a user input form containing 15 or so input fields. This later input will create a datatable with 20 or so columns (5 of which are derived from the user input data). This datatable will then append 1 new row onto an existing postgresql table.

Is this reasonable to do in dash/flask? Thank you!!!

-Hunter

UPDATE

Resolved.

I have edited the code above to the solution I found. I hope it helps!

2 Likes