How to create datatable through callback

Hi, I want to create a datatable using callback but it won’t show the table after I upload the file. Can anyone teach me how to do it?

This is the code :

import base64
import io
import dash
from dash.dependencies import Input, Output, State
import dash_core_components as dcc
import dash_html_components as html
import dash_table
import pandas as pd

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

app.layout = html.Div([
    dcc.Upload(
        id='datatable-upload',
        children=html.Div([
            'Drag and Drop or ',
            html.A('Select Files')
        ]),
        style={
            'width': '100%', 'height': '60px', 'lineHeight': '60px',
            'borderWidth': '1px', 'borderStyle': 'dashed',
            'borderRadius': '5px', 'textAlign': 'center', 'margin': '10px'
        },
    ), 
    html.Div(id='output-data-upload'),
       
])


def parse_contents(contents, filename):
    content_type, content_string = contents.split(',')
    decoded = base64.b64decode(content_string)
    if 'csv' in filename:
        # Assume that the user uploaded a CSV file
       return pd.read_csv(
            io.StringIO(decoded.decode('utf-8')))
    elif 'xls' in filename:
        # Assume that the user uploaded an excel file
        return pd.read_excel(io.BytesIO(decoded))
    


@app.callback(Output('output-data-upload', 'children'),
              [Input('datatable-upload', 'contents')],
              [State('datatable-upload', 'filename')])
def update_output(contents, filename):
    if contents is None:
        return [{}]
    df = parse_contents(contents, filename)   
    return html.Div([
			dash_table.DataTable(
				id='table',
				columns=[{"name": i, "id": i} for i in df.columns],
				data=df.to_dict("records"),
                )				
			])



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

Hi @Yuechean! Are there any errors popping up in the browser console (or the Python console)?

Hi @shammamah. There is an error popping up in the browser console but I don’t know how to solve it.

The error is :
An object was provided as children instead of a component, string, or number (or list of those). Check the children property that looks something like: {}

(This error originated from the built-in JavaScript code that runs Dash apps. Click to see the full stack trace or open your browser’s console.)

I think the problem is in the following line:

if contents is None:
        return [{}]

As the error says, it only takes a component, string or number (or list of those) as children.
You are returning a list of an empty dictionary which is not allowed.

Why not just change it to:

if contents is None:
        return [] # or just None

It works!! @dimark and @shammamah thanks for the reply and help.

1 Like