How can I enable editing on a specific row on a Dash DataTable

Viewed 1168

I want to enable modifications on a specific row on a dash Datatable, so far we can enable editing by column, but I don't want to enable editing on the whole column, I just want to enable it on a specific row. I can highlight the row using style_data_conditional:

style_data_conditional = [
                {
                    "if": {"column_id": x, "row_index": 2},
                    "backgroundColor": 'red',
                    "cursor": "pointer",
                }
                for x in df.columns[2:]
            ]

But I want to make this row also editable.

1 Answers

One approach it so make the whole DataTable editable and make specific rows not editable using css.

import dash
import dash_table
import pandas as pd

df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/solar.csv")

app = dash.Dash(__name__)

app.layout = dash_table.DataTable(
    id="table",
    columns=[{"name": i, "id": i} for i in df.columns],
    data=df.to_dict("records"),
    editable=True,
)


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

When DataTable is not editable a td contains a div with the cell text inside. When it's editable the div with cell text has its opacity set to 0 and an input with the cell value is added.

We can add some css to remove this input and set the opacity of the div with the cell value to 1 for td elements where the data-dash-row attribute does not equal a certain row number:

td:not([data-dash-row="2"]) div.input-cell-value-shadow {
  opacity: 1 !important
}

td:not([data-dash-row="2"]) input {
  display: none;
}

So the styles above make it so only the third row of the DataTable is editable.

Related