Help with displaying data in data table

Hello everyone,

I’m new to dash and plotly, and I need some help with trying to get some data to render in a dash datatable.

app.layout = html.Div([
    html.Div([
        html.Label('Filter Type:'),
        dcc.RadioItems(
            id='filter-type',
            options=[
                {'label': 'All', 'value': 'All'},
                {'label': 'Water Rescue', 'value': 'Water'},
                {'label': 'Mountain or Wilderness Rescue', 'value': 'Mountain'},
                {'label': 'Disaster Rescue or Individual Tracking', 'value': 'Disaster'},
            ],
            value='All'
        )
    ]),
    dash_table.DataTable(id='datatable-id',
                         data=df.to_dict('records'),
                         columns=[{"name": i, "id": i, "deletable": False, "selectable": True} for i in df.columns],
                         editable=True,
                         row_selectable="single", 
                         selected_rows=[0], 
                         filter_action="native",  
                         sort_action="native", 
                         page_action="native", 
                         page_current=0, 
                         page_size=10  
                        ),
        ])
])

@app.callback([Output('datatable-id','data'),
              Output('datatable-id','columns')],
              [Input('filter-type', 'value')])
def update_dashboard(filter_type):
    breed_mappings = {
        'Water': ["Labrador Retriever Mix", "Chesapeake Bay Retriever", "Newfoundland"],
        'Mountain': ["German Shepherd", "Alaskan Malamute", "Old English Sheepdog", "Siberian Husky", "Rottweiler"],
        'Disaster': ["Doberman Pinscher", "German Shepherd", "Golden Retriever", "Bloodhound", "Rottweiler"]
    }

    if filter_type == "All":
        df = pd.DataFrame.from_records(db.getRecordsByQuery({}))
    elif filter_type not in breed_mappings:
        raise Exception("Unknown filter")
    else:
        target_breeds = breed_mappings[filter_type]
        or_conditions = [{"breed": breed} for breed in target_breeds]

        df = pd.DataFrame.from_records(db.getRecordsByQuery({
            "$or": or_conditions,
            "sex_upon_outcome": "Intact Male" if filter_type == "Mountain" else "Intact Female",
            "age_upon_outcome_in_weeks": {"$gte": 20.0, "$lte": 300.0} if filter_type == "Disaster" else {"$gte": 26.0, "$lte": 156.0}
        }))

    
    data = df.to_dict('records')
    columns = [{"name": i, "id": i, "deletable": False, "selectable": True} for i in df.columns]

    return (data, columns)

I am able to successfully retrieve data from my database, but I can’t load the data into the table. I’ve uploaded the error stack here.

I’m using dash 2.0.0.

I’ve tried:

  • Reducing the number of attributes on the DataTable
  • Returning a single data attribute instead of a tuple
  • Turning off debug mode
  • Installing a different version of dash

but I’ve unable to resolve this issue. If someone could please assist me, I’d sincerely appreciate it. Thank you so much in advance!

Hi @dajw916 and welcome to the Dash community :slight_smile:

Nothing looks obviously wrong with the code. From the error message it seems like there is a problem with serializing the data to json format.

For debugging, you could try making a minimal example using a plotly sample dataset. More info on how to do that here: How to Get your Questions Answered on the Plotly Forum

I also recommend using the latest version of dash 2.13.0. And, since you are just getting started, check out Dash AG Grid instead of the DataTable. It won’t solve your problem because the data also needs to be in the same json format, however there are lots of cool features in AG Grid, and if you start with the grid, you won’t have to convert from DataTable later.

2 Likes

Hi @AnnMarieW,

Thank you for responding and providing some helpful information. I just found out the reason why my code wasn’t working. I needed to add this line of code before setting my data variable.

df.drop(columns=['_id'],inplace=True)

MongoDB v5+ appears to return the _id column and this appears to make the app not work properly. Anyways, I’m happy I was able to get the issue solved. Once again, thank you for your time and assistance.

1 Like