Hi,
I am fairly new to Dash. I’ve built my app in two stages which work fine independently but I cannot put them together (on the same page). Here is a minimalist piece of code to demonstrate what I’m trying to do in simple terms. The first stage of my app is a choice of a city (via a dropdown) and the population of a datatable (via the “Initialise app” button). The second stage of the app is an option to edit the data, with the possibility to restore it after any unwanted edits (via the “Restore” button). I don’t know how to put those two stages together. Essentially the first stage provides the data for the second stage to consume it. I’m struggling precisely with that transfer of data or relationship. My simplified code doesn’t work but hopefully you can see what it’s meant to do. Please are you able to edit my code so that it works?
import dash
import pandas as pd
import dash_bootstrap_components as dbc
from dash.dependencies import Input, State, Output
app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
city_dropdown = dash.html.Div(
[
dash.html.Label("Select city", htmlFor="city"),
dash.dcc.Dropdown(
id="city",
options=[{"label": "NYC", "value": 0}, {"label": "LDN", "value": 1}],
placeholder="Select city",
),
]
)
initialise = (dash.html.Button(id="initialise", n_clicks=0, children="Initialise app"),)
tables = dash.html.Div(
children=[
dash.html.Label("trade"),
dash.html.Button("Restore", id="button_e", n_clicks=0),
dash.dash_table.DataTable(
id="table_e",
data=trade.to_dict("records"),
columns=[{"name": i, "id": i, "type": "numeric"} for i in trade.columns],
editable=True,
row_selectable="multi",
),
]
)
app.layout = dbc.Container(
[
dash.html.H2("Test", className="text-center"),
dbc.Row([dbc.Col(city_dropdown), dbc.Col(initialise)]),
dbc.Row(tables),
],
fluid=True,
)
@dash.callback(
Output("trade", "data"),
Input("initialise", "n_clicks"),
State("city_dropdown", "value"),
prevent_initial_call=True,
)
def initialise(n_clicks, city):
if city == "NYC":
trade = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
elif city == "LDN":
trade = pd.DataFrame([[9, 8, 7], [6, 5, 4], [3, 2, 1]])
return trade
if __name__ == "__main__":
app.run_server(debug=True)