The below code functions correctly. The problem is that upon the initial loading of the app, the ID of the datatable cannot be found. I believe this is because it has not yet been created.
How do I avoid this errror?
from dash import dash, dash_table, html
from dash.dependencies import Input, Output, State
import pandas as pd
from dash.exceptions import PreventUpdate
app = dash.Dash(__name__, prevent_initial_callbacks=True)
app.layout = html.Div([
html.Button('start', id='button1'),
html.Button('start', id='button2'),
html.Div(id='div1'),
html.Div(id='div2')
])
@app.callback(
Output('div1', 'children'),
Input('button1', 'n_clicks'),
)
def generate_upload_file(n_clicks):
if n_clicks:
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder2007.csv')
data_dict = df.to_dict('records')
headers_list = list(df.columns.values)
headers_dict = ([{'id': _, 'name': _} for _ in headers_list])
return dash_table.DataTable(
id='datatable1',
data=data_dict,
columns=headers_dict,
filter_action="native",
sort_action="native",
sort_mode="multi",
row_deletable=True,
page_action="native",
page_current= 0,
page_size= 10,
)
else: raise PreventUpdate
@app.callback(
Output('div2', 'children'),
Input('button2', 'n_clicks'),
State('datatable1', 'data'),
)
def create_df(n_clicks, datatable_rows):
if n_clicks:
df = pd.DataFrame.from_dict(datatable_rows)
print(df)
else: raise PreventUpdate
if __name__ == '__main__':
app.run_server(debug=True)