Black Lives Matter. Please consider donating to Black Girls Code today.
Dash HoloViews is now available! ✅Check out the new docs.

Dash callbacks not working

I am using dash to create an interactive page. I have many callbacks happening to render the controls. There are helper methods inside the callback to get the data and other information. sometimes the callback do not execute and when it executes sometimes it do not step into the helper methods. No errors are thrown. Anyone had issues similar to this?

Here is my layout
tab1_layout = [html.Div(“Enrollment Count for Elementary School” , className=“subHeader”),
html.Div(“Store data into hidden div”,
n_clicks=1,
id=‘store-data-hidden-div’,
style={‘display’: ‘none’}),
#race drop down
html.Div([
html.Label(“Race:”, id=“racelabel”),
dcc.Dropdown(
id=‘racedropdown’,
options=[
{‘label’: ‘All’, ‘value’: ‘all’},
{‘label’: ‘Asian’, ‘value’: ‘a’},
{‘label’: ‘Black’, ‘value’: ‘b’},
{‘label’: ‘Hispanic’, ‘value’: ‘h’},
{‘label’: ‘Indian’, ‘value’: ‘i’},
{‘label’: ‘Multiracial’, ‘value’: ‘m’},
#{‘label’: ‘Other’, ‘value’: ‘other’},
{‘label’: ‘White’, ‘value’: ‘w’},

            ],
            value='all'
        ),
            #ELL Drop down                
            html.Label("ELL:", id="elllabel"),                       
            dcc.Dropdown(
            id='elldropdown',
            options=[
                {'label': 'All', 'value': 'all'},                                                     
                {'label': 'SWD', 'value': 'swd'},
                {'label': 'Gifted', 'value': 'gifted'},
                {'label': 'Migrant', 'value': 'migrant'},                            
                {'label': 'LY', 'value': 'ly'},                            
                {'label': 'LF', 'value': 'lf'},
                {'label': 'Free Reduced', 'value': 'freereduced'},                           
                        
            ],
            value='all'
        )],className="row"),
           dcc.Graph(id = "elementarygraph"),
              #slider

            html.Div([        
                dcc.Slider(
                min=1,
                max=5,
                marks={
                    #0: {'label': 'All Grades', 'style': {'color': '#f50'}},
                    1: {'label': 'Grade 1', 'style': {'color': '#77b0b1'}},
                    2: {'label': 'Grade 2', 'style': {'color': '#77b0b1'}},
                    3: {'label': 'Grade 3', 'style': {'color': '#77b0b1'}},
                    4: {'label': 'Grade 4', 'style': {'color': '#77b0b1'}},  
                    5: {'label': 'Grade 5', 'style': {'color': '#77b0b1'}},       
                },
                className="displaySlider",
                id="Schoolslider",
                value=0
                    ),
                     
                html.Div(id='slider-container'),
            ]) ,
           ]

tab2_layout = [html.Div(“Enrollment Count for Midddle School” , className=“subHeader”),
html.Div(“Store data into hidden div”,
n_clicks=2,
id=‘store-data-hidden-div’,
style={‘display’: ‘none’}),

            #race drop down
            html.Div([
            html.Label("Race:", id="racelabel"),                       
            dcc.Dropdown(
            id='racedropdown',
            options=[
                {'label': 'All', 'value': 'all'},                                                     
                {'label': 'Asian', 'value': 'a'},
                {'label': 'Black', 'value': 'b'},
                {'label': 'Hispanic', 'value': 'h'},                            
                {'label': 'Indian', 'value': 'i'},                            
                {'label': 'Multiracial', 'value': 'm'},
                #{'label': 'Other', 'value': 'other'},
                {'label': 'White', 'value': 'w'},  
                        
            ],
            value='all'
        ),

        #ELL Drop down
           
            html.Label("ELL:", id="elllabel"),                       
            dcc.Dropdown(
            id='elldropdown',
            options=[
                {'label': 'All', 'value': 'all'},                                                     
                {'label': 'SWD', 'value': 'swd'},
                {'label': 'Gifted', 'value': 'gifted'},
                {'label': 'Migrant', 'value': 'migrant'},                            
                {'label': 'LY', 'value': 'ly'},                            
                {'label': 'LF', 'value': 'lf'},
                {'label': 'Free Reduced', 'value': 'freereduced'},                           
                        
            ],
            value='all'
        ),
             ],className="row"),
           dcc.Graph(id = "middlegraph"),
            #slider

            html.Div([        
                dcc.Slider(
                min=6,
                max=8,
                marks={
                    0: {'label': 'All Grades', 'style': {'color': '#f50'}},
                    6: {'label': 'Grade 6', 'style': {'color': '#77b0b1'}},
                    7: {'label': 'Grade 7', 'style': {'color': '#77b0b1'}},
                    8: {'label': 'Grade 8', 'style': {'color': '#77b0b1'}},
                                       
                },
                className="displaySlider",
                id="Schoolslider",
                value=0
                    ),
                     
                html.Div(id='slider-container'),
            ]) ,



           ]

tab3_layout = [html.Div(“Enrollment Count for High School”, className=“subHeader”),
html.Div(“Store data into hidden div”,
n_clicks=3,
id=‘store-data-hidden-div’,
style={‘display’: ‘none’}),

            #race drop down
            html.Div([
            html.Label("Race:", id="racelabel"),                       
            dcc.Dropdown(
            id='racedropdown',
            options=[
                {'label': 'All', 'value': 'all'},                                                     
                {'label': 'Asian', 'value': 'a'},
                {'label': 'Black', 'value': 'b'},
                {'label': 'Hispanic', 'value': 'h'},                            
                {'label': 'Indian', 'value': 'i'},                            
                {'label': 'Multiracial', 'value': 'm'},
                #{'label': 'Other', 'value': 'other'},
                {'label': 'White', 'value': 'w'},  
                        
            ],
            value='all'
        ),

        #ELL Drop down
            
            html.Label("ELL:", id="elllabel"),                       
            dcc.Dropdown(
            id='elldropdown',
            options=[
                {'label': 'All', 'value': 'all'},                                                     
                {'label': 'SWD', 'value': 'swd'},
                {'label': 'Gifted', 'value': 'gifted'},
                {'label': 'Migrant', 'value': 'migrant'},                            
                {'label': 'LY', 'value': 'ly'},                            
                {'label': 'LF', 'value': 'lf'},
                {'label': 'Free Reduced', 'value': 'freereduced'},                           
                        
            ],
            value='all'
        )],className="row"),
           dcc.Graph(id = "highgraph"),
            #slider

            #html.Div([        
                dcc.Slider(
                min=9,
                max=12,
                marks={
                  #  0: {'label': 'All Grades', 'style': {'color': '#f50'}},
                    9: {'label': 'Grade 9', 'style': {'color': '#77b0b1'}},
                    10: {'label': 'Grade 10', 'style': {'color': '#77b0b1'}},
                    11: {'label': 'Grade 11', 'style': {'color': '#77b0b1'}},
                    12: {'label': 'Grade 12', 'style': {'color': '#77b0b1'}},                    
                },
                className="displaySlider",
                id="Schoolslider",
                value=0
                    ),
                     
                html.Div(id='slider-container'),               

            dt.DataTable(
            #rows=[{}], # initialise the rows
            rows=enrolldf.to_dict('records'),
            row_selectable=True,
            filterable=True,
            sortable=True,
            selected_row_indices=[],
            id='datatable'
          ),
       
                   ]

app.layout = html.Div([
# hidden Div for storing data needed for graphs
html.Div(id=‘graph-data-json-dump’, style={‘display’: ‘none’}),
# Title
html.H2(“District Dashboard”, className=“mainHeader”),
dcc.Tabs(id=“tabs”, value=3, children=[
dcc.Tab(label=‘Elementary School’, value=1),
dcc.Tab(label=‘Middle School’, value=2),
dcc.Tab(label=‘High School’, value=3),
]),

# Tab-layout
html.Div(id='tab-layout'),    

])

Here are the callbacks

@app.callback(dash.dependencies.Output(‘tab-layout’, ‘children’),
[dash.dependencies.Input(‘tabs’, ‘value’)])
def call_tab_layout(tab_value):
if tab_value == 1:
return tab1_layout
elif tab_value == 2:
return tab2_layout
elif tab_value == 3:
return tab3_layout
else:
html.Div()

@app.callback(dash.dependencies.Output(‘datatable’, ‘rows’), [dash.dependencies.Input(‘tabs’, ‘value’)])
def update_datatable(tab):

_df=populateenrollmenttableforchart(tab)        
 return  _df.to_dict('rows')        

def populateenrollmenttableforchart(tab):
try:
cursor = cnxn.cursor()
sql= "select Studentid,firstname, lastname, s.schoolcode, grade,gender, race, freereducedlunch,ell,eseswd, esegifted,migrant,outofzone,dob from students s "
if(tab == 3):
sql= “select Studentid,firstname, lastname, s.schoolcode, grade,gender, race, freereducedlunch,ell,eseswd, esegifted,migrant,outofzone,dob from students s inner join schools sc on s.schoolcode=sc.schoolcode where sc.schooltype in (‘H’) order by schoolname”
demodf = pd.read_sql(sql, cnxn)
result= demodf
return result
except Exception as e:
print(e)
finally:
cursor.close

#sending data to hidden div from tab1
@app.callback(dash.dependencies.Output(‘graph-data-json-dump’, ‘children’),
[dash.dependencies.Input(‘store-data-hidden-div’, ‘n_clicks’),
dash.dependencies.Input(‘racedropdown’, ‘value’),
dash.dependencies.Input(‘elldropdown’, ‘value’),
dash.dependencies.Input(‘Schoolslider’,‘value’),
])
def store_data_to_hidden_div(nclick, race,ell, grade):
#if nclick >0:
#df = pd.DataFrame({‘x_axis’:[6,4,9],
# ‘y_axis’:[4,2,7]})
df= populateenrollmentgraph(nclick, race,ell, grade)

    return df.to_json(orient = 'split')

def populateenrollmentgraph(nclick, race,ell, grade):
try:
cursor = cnxn.cursor()
racevalue=‘all’
if(grade != 0 and grade < 10):
grade = ‘0’ + str(grade)
sql= “execute dbo.Proc_Students_Enrollment_Summary @filterrace = ‘%s’” % race + " , @filtergrade = ‘%s’" % grade + " , @filterell = ‘%s’" % ell
demodf = pd.read_sql(sql, cnxn)
if(nclick == 1):
demodf = demodf[demodf.schooltype.isin([‘E’])]
if(nclick ==2):
demodf = demodf[demodf.schooltype.isin([‘M’])]
if(nclick ==3):
demodf = demodf[demodf.schooltype.isin([‘H’])]

    yaxisvalue = demodf['schoolname']
    xaxisvalue = demodf['enrollmentcount']
            
   
 #   result = pd.DataFrame({'x_axis':demodf['enrollmentcount'],'y_axis':demodf['schoolname']})  
    result = pd.DataFrame({'x_axis':xaxisvalue,'y_axis':demodf['schoolname']})        
    return result   
except Exception as e:
    print(e)      
finally:
    cursor.close 

#plotting bar graph in same tab

@app.callback(dash.dependencies.Output(‘elementarygraph’, ‘figure’),
[dash.dependencies.Input(‘graph-data-json-dump’, ‘children’),
#dash.dependencies.Input(‘create-bar-chart’, ‘n_clicks’)
dash.dependencies.Input(‘racedropdown’, ‘value’),
dash.dependencies.Input(‘elldropdown’, ‘value’),
])

def create_elementary_chart(json_dump, race, ell):

    json_dump = json.loads(json_dump)
    json_dump_df = pd.DataFrame(json_dump['data'], columns=json_dump['columns'])

    data = [go.Bar(
        x = json_dump_df['x_axis'].values,
        y = json_dump_df['y_axis'].values,
        orientation='h',   
   #     opacity=0.3,
        text = json_dump_df['y_axis'].values,
        marker = dict(color = 'rgba(50, 171, 96, 0.6)',
        line = dict(color = 'rgba(50, 171, 96, 0.6)', width = 3)
         ),             
        name = "Enrollment Data")]
    layout = go.Layout(
            xaxis=dict(
                zeroline=False,
                showline=False,
                showticklabels=True,
                tickmode = "auto", 
                ticks= "",
                anchor = "y",
                showgrid=True,                                     
                autorange = False,  
                range=[0, 1000],                                    
                side="top",
                type="linear",
                domain=[0.15, 1],                      
            ),
            yaxis=dict(
                showline=False,
                showticklabels=True,                                
                anchor = "x",                                    
                showgrid=False,                                     
                autorange = True,                    
                side="left",
           #     type="category", 
                domain=[0.5, 0.5],                      
                
            ),
            barmode='stack',
            bargap=0,                
            paper_bgcolor='rgb(248, 248, 255)',
            plot_bgcolor='rgb(248, 248, 255)',
            margin=dict(
                l=0,
                r=10,
                t=70,
                b=80
            ),
            showlegend=True,
            hovermode='y',                
            
     )
    fig = go.Figure(data = data, layout=layout)
    return fig

#plotting second graph in next tab
@app.callback(dash.dependencies.Output(‘middlegraph’, ‘figure’),
[dash.dependencies.Input(‘graph-data-json-dump’, ‘children’),
# dash.dependencies.Input(‘create-line-chart’, ‘n_clicks’)
dash.dependencies.Input(‘racedropdown’, ‘value’),
dash.dependencies.Input(‘elldropdown’, ‘value’),

           ])

def create_middle_chart(json_dump, race, ell):

    json_dump = json.loads(json_dump)
    json_dump_df = pd.DataFrame(json_dump['data'], columns=json_dump['columns'])
   #chart 

    data = [go.Bar(
        x = json_dump_df['x_axis'].values,
        y = json_dump_df['y_axis'].values,
        orientation='h',   
    #    opacity=0.1,
        text = json_dump_df['y_axis'].values,
        marker = dict(color = 'rgba(50, 171, 96, 0.6)',
        line = dict(color = 'rgba(50, 171, 96, 1.0)', width = 3)
         ),             
        name = "Enrollment Data")]
    layout = go.Layout(
            xaxis=dict(
                zeroline=False,
                showline=False,
                showticklabels=True,
                tickmode = "auto", 
                ticks= "",
                anchor = "y",
                showgrid=True,                                     
                autorange = True,  
                range=[0, 2500],                                    
                side="top",
                type="linear",
                domain=[0.15, 1],                      
            ),
            yaxis=dict(
                showline=False,
                showticklabels=True,                                
                anchor = "x",                                    
                showgrid=False,                                     
                autorange = True,                    
                side="left",
           #     type="category", 
                domain=[0.5, 0.5],                      
                
            ),
            barmode='stack',
            bargap=0,                
            paper_bgcolor='rgb(248, 248, 255)',
            plot_bgcolor='rgb(248, 248, 255)',
            margin=dict(
                l=0,
                r=10,
                t=70,
                b=80
            ),
            showlegend=True,
            hovermode='y',                
            
     )
    fig = go.Figure(data = data, layout=layout)
    return fig


#plotting third graph in next tab

@app.callback(dash.dependencies.Output(‘highgraph’, ‘figure’),
[dash.dependencies.Input(‘graph-data-json-dump’, ‘children’),
# dash.dependencies.Input(‘create-line-chart’, ‘n_clicks’)
dash.dependencies.Input(‘racedropdown’, ‘value’),
dash.dependencies.Input(‘elldropdown’, ‘value’),
])
def create_high_chart(json_dump, race,ell):

    json_dump = json.loads(json_dump)
    json_dump_df = pd.DataFrame(json_dump['data'], columns=json_dump['columns'])
   #chart 

    data = [go.Bar(
        x = json_dump_df['x_axis'].values,
        y = json_dump_df['y_axis'].values,
        orientation='h',   
    #    opacity=0.1,
        text = json_dump_df['y_axis'].values,
        marker = dict(color = 'rgba(50, 119, 179, 0.6)',
        line = dict(color = 'rgba(50, 119, 179, 1.0)', width = 3)
         ),             
        name = "Enrollment Data")]
    layout = go.Layout(
            xaxis=dict(
                zeroline=False,
                showline=False,
                showticklabels=True,
                tickmode = "auto", 
                ticks= "",
                anchor = "y",
                showgrid=True,                                     
                autorange = True,  
                range=[0, 2500],                                    
                side="top",
                type="linear",
                domain=[0.15, 1],                      
            ),
            yaxis=dict(
                showline=False,
                showticklabels=True,                                
                anchor = "x",                                    
                showgrid=False,                                     
                autorange = True,                    
                side="left",
           #     type="category", 
                domain=[0.5, 0.5],                      
                
            ),
            barmode='stack',
            bargap=0,                
            paper_bgcolor='rgb(248, 248, 255)',
            plot_bgcolor='rgb(248, 248, 255)',
            margin=dict(
                l=0,
                r=10,
                t=70,
                b=80
            ),
            showlegend=True,
            hovermode='y',                
            
     )
    fig = go.Figure(data = data, layout=layout)
    return fig

Problem is populateenrollmentgraph is not called when I add the callback to update the datatable

Your code is far too long to read in a post, and I can’t copy and paste and run it because it depends on external connections I don’t have access to.

If you make a short simple example that someone else can execute and view the problem then it’s very easy to help.

However, one guess in the dark:

@app.callback(dash.dependencies.Output('datatable', 'rows'), [dash.dependencies.Input('tabs', 'value')])
def update_datatable(tab):
    _df=populateenrollmenttableforchart(tab)
    return  _df.to_dict('rows')

If you look at the documentation the property that df.to_dict('rows') goes to is “data” not “rows”, so maybe try:

@app.callback(dash.dependencies.Output('datatable', 'data'), [dash.dependencies.Input('tabs', 'value')])
def update_datatable(tab):
    _df=populateenrollmenttableforchart(tab)
    return  _df.to_dict('rows')

Thank you. will try that . I will try to post a simple example