I just did an experiment to see why my code doesn’t seem to work the same way as the one in the example presented here: https://dash.plotly.com/datatable/editable
Here’s my code:
import dash
import dash_table
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
from dash.exceptions import PreventUpdate
import pandas as pd
app = dash.Dash(external_stylesheets=[dbc.themes.BOOTSTRAP])
forecasts = ["Demand Plan", "Stat Forecast", "Year -1", "% growth (-1)", "Year -2", "% growth (-2)"]
app.layout = html.Div([
dash_table.DataTable(
id = 'table',
columns = [{'name': 'Forecasts', 'id': 'Forecasts'}] + [{
'name': '{}'.format(j),
'id': 'column-{}'.format(i),
'deletable': True,
'renamable': True
} for i,j in zip(range(5), [1,2,3,4,5])],
data=[
dict(Forecasts=i, **{'column-{}'.format(k): 0*j for k in range(5)})
for i, j in zip(forecasts, range(len(forecasts)))
],
editable = True,
row_selectable='multi',
#row_deletable=True,
selected_rows=[1],
selected_row_ids=['Stat Forecast'],
fixed_columns={ 'headers': True, 'data': 1 },
style_cell={'textAlign': 'center'},
style_table={'overflowX': 'scroll',
'minWidth': '100%',
'padding':'10px'},
css=[{"selector": ".show-hide", "rule": "display: none"}]
),
html.Button('Add Row', id='add-row-button', n_clicks=0),
])
@app.callback(
Output('table', 'data'),
[Input('add-row-button', 'n_clicks')],
[State('table', 'data'),
State('table', 'columns')])
def add_row(n_clicks, rows, columns):
rows=[
dict(id=i, **{'column-{}'.format(k): j+1 for k in range(len(columns))})
for i, j in zip(forecasts, range(len(forecasts)))
]
if n_clicks > 0:
rows.append({c['id']: '' for c in columns})
return rows
if __name__ == '__main__':
app.run_server(debug = True)
If the callback you’re using to append rows to the table also involves modifying the rows somehow, the “add row” button only ever appends one row to the table. If you press it again, the last appended row is simply overwritten. Still not sure why this is so and how to get around it, but progress. @chriddyp, can you please help?