Error Loading Layout!

import pandas as pd
import plotly.express as px  # (version 4.7.0 or higher)
import plotly.graph_objects as go
from datetime import datetime
import dash
from dash import Dash, dcc, html, Input, Output  # pip install dash (version 2.0.0 or higher)



def get_key_from_value(dictionary, target_value):
    for key, value in dictionary.items():
        if value == target_value:
            return key
    return None

app = Dash(__name__)

# -- Import and clean data (importing csv into pandas)
df = pd.read_excel("FAC Hourly Data.xlsx")


df['FAC hourly data_start date_dt'] = pd.to_datetime(df['FAC hourly data_start date_dt'], dayfirst=True)
df['weekday'] = df["FAC hourly data_start date_dt"].dt.weekday
print(df)

timenow = datetime.now().hour
if timenow > 18:
    timenow = 18
elif timenow < 9:
    timenow = 9
weekday = datetime.now().weekday

# ------------------------------------------------------------------------------
# App layout
app.layout = html.Div(
    [
        html.H1("Canteen Data Ngee Ann Polytechnic", style={'text-align': 'center'}),
        html.Label("Hour:",style={'fontSize':30, 'textAlign':'center'}),

        dcc.Dropdown(id="slct_hour",
                    
                    options=[
                        {"label": "9am", "value": 9},
                        {"label": "10am", "value": 10},
                        {"label": "11am", "value": 11},
                        {"label": "12pm", "value": 12},
                        {"label": "1pm", "value": 13},
                        {"label": "2pm", "value": 14},
                        {"label": "3pm", "value": 15},
                        {"label": "4pm", "value": 16},
                        {"label": "5pm", "value": 17},
                        {"label": "6pm", "value": 18}],
                    multi=False,
                    value = timenow,
                    
                    
                    
                    style={'width': "30%","display":"flex"}
                    ),
        html.Label("Day:",style={'fontSize':30, 'textAlign':'center'}),
        dcc.Dropdown(id="slct_weekday",
                    
                    options=[
                        {"label": "Mon", "value": 0},
                        {"label": "Tue", "value": 1},
                        {"label": "Wed", "value": 2},
                        {"label": "Thu", "value": 3},
                        {"label": "Fri", "value": 4}],
                        
                    multi=False,
                    value = weekday,
                    
                    
                    
                    style={'width': "30%","display":"flex"}
                    ),

        html.Div(id='output_container', children=[]),
        html.Br()

        

])



# ------------------------------------------------------------------------------
# # Connect the Plotly graphs with Dash Components
@app.callback(
    [Output(component_id='output_container', component_property='children'),
     Output(component_id='canteenchart', component_property='figure')],
    [Input('slct_hour','value'),Input('slct_weekday','value')])
   
def update_graph(selected_hour,selected_weekday):

    

    container = "The hour chosen by the user was: {}".format(selected_hour)

    dff = df.copy()
    dff = dff[dff["FAC hourly data_Hour"] == selected_hour]
    dff = dff[dff["weekday"] == selected_weekday]
    fig = px.bar(

        dff,
        x="FAC hourly data_Hour",
        y="%perc",
        color="FAC hourly data_Blk",
        barmode="group",  # This will display bars side by side for each hour
        labels={"FAC hourly data_Hour": "Hour of the Day", "%perc": "Percentage Filled"},
        title="Percentage of Canteens Filled per Hour",
    )
    
    


    return[dcc.Graph(figure=fig)]


# ------------------------------------------------------------------------------
if __name__ == '__main__':
    app.run_server(debug=False)

Hey guys the above shows my code for my dash web app, however I keep getting the error Error loading layout on my webpage. Any feedback would be appreciated. Thanks a bunch!

here is the link to my dataset : Loading Google Sheets

    • List item

Hello @ethanliewsh,

Welcome to the community!

Error loading layout means something about your code isnt working right.

You should change your debug=False to debug=True, this might help you figure out where the layout is running into an issue. :slight_smile:

1 Like

[2023-07-27 23:37:11,981] ERROR in app: Exception on /_dash-layout [GET]
Traceback (most recent call last):
File “C:\Users\ethan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\flask\app.py”, line 2529, in wsgi_app
response = self.full_dispatch_request()
File “C:\Users\ethan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\flask\app.py”, line 1825, in full_dispatch_request
rv = self.handle_user_exception(e)
File “C:\Users\ethan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\flask\app.py”, line 1823, in full_dispatch_request
rv = self.dispatch_request()
File “C:\Users\ethan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\flask\app.py”, line 1799, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
File “C:\Users\ethan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\dash\dash.py”, line 690, in serve_layout
to_json(layout),
File “C:\Users\ethan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\dash_utils.py”, line 23, in to_json
return to_json_plotly(value)
File “C:\Users\ethan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\plotly\io_json.py”, line 143, in to_json_plotly
json.dumps(plotly_object, cls=PlotlyJSONEncoder, **opts), swap_json
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\json_init
.py", line 238, in dumps
**kw).encode(obj)
File “C:\Users\ethan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages_plotly_utils\utils.py”, line 59, in encode
encoded_o = super(PlotlyJSONEncoder, self).encode(o)
File “C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\json\encoder.py”, line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File “C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\json\encoder.py”, line 257, in iterencode
return _iterencode(o, 0)
File “C:\Users\ethan\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages_plotly_utils\utils.py”, line 136, in default
return _json.JSONEncoder.default(self, obj)
File “C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\json\encoder.py”, line 179, in default
raise TypeError(f’Object of type {o.class.name} ’
TypeError: Object of type builtin_function_or_method is not JSON serializable
127.0.0.1 - - [27/Jul/2023 23:37:11] “GET /_dash-layout HTTP/1.1” 500 -

Sorry im new to python and debugging in general, any ideas what is wrong with my code?

Hi @ethanliewsh

The important part of this error message is this line:

raise TypeError(f’Object of type {o.class .name } ’
TypeError: Object of type builtin_function_or_method is not JSON serializable

So this means that something is being passed that cannot be displayed in the browser

The problem is in this dropdown:

                 dcc.Dropdown(id="slct_weekday",

                     options=[
                         {"label": "Mon", "value": 0},
                         {"label": "Tue", "value": 1},
                         {"label": "Wed", "value": 2},
                         {"label": "Thu", "value": 3},
                         {"label": "Fri", "value": 4}],

                     multi=False,
                     value=weekday,

                     style={'width': "30%", "display": "flex"}
                     ),

you have weekday defined like this:

weekday = datetime.now().weekday


If you do add

print(weekday)

You will see that it is the class:

< built-in method weekday of datetime.datetime object at 0x7efccfff0cc0>

If you change it to this it will work:

weekday = datetime.now().weekday()
2 Likes

Thanks a bunch it worked!

2 Likes