JavaScript error while navigating through the application

Hello everyone, this is my first post on the forum.

I’m working on an employee management application, and I’m using the Dash library in conjunction with Flask for this purpose. However, I’m encountering an error that appears randomly, and I’m not sure of the cause. Sometimes when navigating through the application, the following appears:

Cannot read properties of null (reading 'length')
(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.)
TypeError: Cannot read properties of null (reading 'length')

    at _loop (http://127.0.0.1/_dash-component-suites/dash/dash-renderer/build/dash_renderer.v2_15_0m1708524583.dev.js:3879:47)

    at BaseTreeContainer.getComponent (http://127.0.0.1/_dash-component-suites/dash/dash-renderer/build/dash_renderer.v2_15_0m1708524583.dev.js:3967:16)

    at BaseTreeContainer.render (http://127.0.0.1/_dash-component-suites/dash/dash-renderer/build/dash_renderer.v2_15_0m1708524583.dev.js:4008:19)

    at finishClassComponent (http://127.0.0.1/_dash-component-suites/dash/deps/react-dom@16.v2_15_0m1708524583.14.0.js:17295:33)

    at updateClassComponent (http://127.0.0.1/_dash-component-suites/dash/deps/react-dom@16.v2_15_0m1708524583.14.0.js:17245:26)

    at beginWork (http://127.0.0.1/_dash-component-suites/dash/deps/react-dom@16.v2_15_0m1708524583.14.0.js:18755:18)

    at HTMLUnknownElement.callCallback (http://127.0.0.1/_dash-component-suites/dash/deps/react-dom@16.v2_15_0m1708524583.14.0.js:182:16)

    at Object.invokeGuardedCallbackDev (http://127.0.0.1/_dash-component-suites/dash/deps/react-dom@16.v2_15_0m1708524583.14.0.js:231:18)

    at invokeGuardedCallback (http://127.0.0.1/_dash-component-suites/dash/deps/react-dom@16.v2_15_0m1708524583.14.0.js:286:33)

    at beginWork$1 (http://127.0.0.1/_dash-component-suites/dash/deps/react-dom@16.v2_15_0m1708524583.14.0.js:23338:9)
type or paste code here

When I activate the Flask login system, the error appears more frequently, sometimes even preventing the page from loading. I’m not sure if there’s any connection with this.

Thank you in advance for your attention.

Hello @shengtai,

Welcome to the community!

Try updating to using Dash 2.16.1, I believe that there was an issue with 2.15.0 which seems to be the version you are using.

Thank you for the warm welcome to the community!

I appreciate the suggestion. I actually updated to Dash 2.16.1 as you recommended, but unfortunately, the error still persists. It seems that the issue remains unresolved even after the update.

If you have any further suggestions , I’d greatly appreciate them.

Thank you again for your help.

(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.)
TypeError: Cannot read properties of null (reading 'length')

    at _loop (http://127.0.0.1/_dash-component-suites/dash/dash-renderer/build/dash_renderer.v2_16_1m1711584002.dev.js:3915:47)

    at BaseTreeContainer.getComponent (http://127.0.0.1/_dash-component-suites/dash/dash-renderer/build/dash_renderer.v2_16_1m1711584002.dev.js:4003:16)

    at BaseTreeContainer.render (http://127.0.0.1/_dash-component-suites/dash/dash-renderer/build/dash_renderer.v2_16_1m1711584002.dev.js:4044:19)

    at finishClassComponent (http://127.0.0.1/_dash-component-suites/dash/deps/react-dom@16.v2_16_1m1711584002.14.0.js:17295:33)

    at updateClassComponent (http://127.0.0.1/_dash-component-suites/dash/deps/react-dom@16.v2_16_1m1711584002.14.0.js:17245:26)

    at beginWork (http://127.0.0.1/_dash-component-suites/dash/deps/react-dom@16.v2_16_1m1711584002.14.0.js:18755:18)

    at HTMLUnknownElement.callCallback (http://127.0.0.1/_dash-component-suites/dash/deps/react-dom@16.v2_16_1m1711584002.14.0.js:182:16)

    at Object.invokeGuardedCallbackDev (http://127.0.0.1/_dash-component-suites/dash/deps/react-dom@16.v2_16_1m1711584002.14.0.js:231:18)

    at invokeGuardedCallback (http://127.0.0.1/_dash-component-suites/dash/deps/react-dom@16.v2_16_1m1711584002.14.0.js:286:33)

    at beginWork$1 (http://127.0.0.1/_dash-component-suites/dash/deps/react-dom@16.v2_16_1m1711584002.14.0.js:23338:9)

It seems that you are passing something in the code that the system doesn’t like.

Any other help, we will need to see your code. :grin:

You can also make a How to write a Minimal Reproducible Example (MRE) for us to reproduce the app.

I investigated the code and conducted some tests, and I noticed that the error only occurs on a specific screen, and only occasionally. The code for this screen is provided below:

from dash import dcc, Input, Output, html, callback
import dash_bootstrap_components as dbc
import pandas as pd
import locale

import connect

# Defina a localidade para o Brasil (pt_BR)
locale.setlocale(locale.LC_ALL, 'pt_BR.UTF-8')

df_funcao = pd.read_sql_query("SELECT * FROM df_funcao", connect.engine_2)
funcao_aux = df_funcao.to_dict(orient='records')

df_filhos = pd.read_sql_query("SELECT * FROM df_filhos", connect.engine_2)
filhos_colaboradores_aux = df_filhos.to_dict()

df_cadastro = pd.read_sql_query("SELECT * FROM df_cadastro", connect.engine_2)
colaboradores_aux = df_cadastro.to_dict()

df_certificacao = pd.read_sql_query("SELECT * FROM df_certificacao", connect.engine_2)

layout_simulacao = html.Div([
    dbc.Card([
        dbc.CardHeader("Simulação de benefícios"),
        dbc.CardBody([
            dbc.Card([
                dbc.CardBody([
                    dbc.Row([
                        dbc.Col([
                            dbc.Label("Formação Acadêmica "),
                            dcc.Dropdown(options=df_certificacao['nivel_de_ensino'],
                                         id="formacao_academica_simulacao", persistence=True,
                                         persistence_type='memory'),
                        ], width=4),
                        dbc.Col([
                            dbc.Label("Filho (até dois anos) "),
                            dbc.Input(placeholder="Digite apenas numeros",
                                      id="filho_2_anos_simulacao", type='number',
                                      min=0, persistence=True, persistence_type='memory')
                        ], width=4),
                        dbc.Col([
                            dbc.Label("Filho com deficiencia "),
                            dbc.Input(placeholder="Digite apenas numeros",
                                      id="filho_deficiencia_simulacao", type='number',
                                      min=0, persistence=True, persistence_type='memory')
                        ], width=4)
                    ]),
                    dbc.Row([
                        dbc.Col([
                            dbc.Label("Função"),
                            dcc.Dropdown(placeholder="Função", id="funcao",
                                         options=df_funcao['funcao'], persistence=True, persistence_type='memory'),
                        ], width=4),
                        dbc.Col([
                            dbc.Label("Categoria"),
                            dcc.Dropdown(placeholder="categoria", id="categoria", persistence=True,
                                         persistence_type='memory'),
                        ], width=4),
                    ]),
                ])
            ]),
        ]),
        dbc.CardHeader('Simulação'),
        dbc.CardBody([
            dbc.Row([
                html.Div(id='table')
            ])

        ]),

    ]),
], style={"background-color": "rgba(17, 140, 79, 0.05)"})


def criar_tabela(categoria, df):
    linhas = []
    for chave, valor in df.items():
        linhas.append(html.Tr([html.Td(chave), html.Td(valor)]))

    return dbc.Table(
        # Cabeçalho da tabela
        children=[
                     html.Thead(html.Tr(
                         [html.Th(categoria, style={'width': '50%', 'height': '50%'}),
                          html.Th(style={'width': '50%'})]))
                 ] +
                 # Corpo da tabela
                 [html.Tbody(linhas)],
        # Adicionando estilos à tabela
        borderless=False,
        hover=True,
        responsive=True,
        bordered=False,
    )


@callback(
    Output('table', 'children'),
    Input("formacao_academica_simulacao", "value"),
    Input("filho_2_anos_simulacao", "value"),
    Input("filho_deficiencia_simulacao", "value"),
    Input("funcao", "value"),
)
def simulacao(formacao, filho_2_anos, filho_deficiencia, funcao):
    try:
        salario = df_funcao[df_funcao['funcao'] == funcao]['salario'].values[0]
    except:
        salario = 0
    try:
        premio_formacao = df_certificacao[df_certificacao['nivel_de_ensino'] == formacao]['premio'].values[
                              0] * salario
    except:
        premio_formacao = 0
    try:
        auxilio_creche = 120 * filho_2_anos
    except:
        auxilio_creche = 0
    try:
        auxilio_deficiencia = 120 * filho_deficiencia
    except:
        auxilio_deficiencia = 0

    # Formate o salário como moeda brasileira

    premio_assiduidade = 235
    vale_alimentacao = 235
    premio_funcao = 250
    descontos_inss = salario * 0.11
    descontos_sindimetal = 26.68

    salario_formatado = locale.currency(salario, grouping=True)
    premio_assiduidade_formatado = locale.currency(235, grouping=True)
    vale_alimentacao_formatado = locale.currency(235, grouping=True)
    premio_funcao_formatado = locale.currency(250, grouping=True)
    premio_formacao_formatado = locale.currency(premio_formacao, grouping=True)
    descontos_inss_formatado = locale.currency(descontos_inss, grouping=True)
    descontos_sindimetal_formatado = locale.currency(descontos_sindimetal, grouping=True)
    auxilio_creche_formatado = locale.currency(int(auxilio_creche), grouping=True)
    auxilio_deficiencia_formatado = locale.currency(int(auxilio_deficiencia), grouping=True)

    receitas_total = (salario + premio_assiduidade + vale_alimentacao + premio_funcao +
                      premio_formacao + auxilio_creche + auxilio_deficiencia)
    premiacao_total = (premio_assiduidade + vale_alimentacao + premio_funcao +
                       premio_formacao + auxilio_creche + auxilio_deficiencia)
    descontos_total = (descontos_inss + descontos_sindimetal)

    total_liquido = receitas_total - descontos_total

    receitas_total_formatado = locale.currency(receitas_total, grouping=True)
    premiacao_total_formatado = locale.currency(premiacao_total, grouping=True)
    descontos_total_formatado = locale.currency(descontos_total, grouping=True)
    total_liquido_formatado = locale.currency(total_liquido, grouping=True)

    # Dados
    df = {
        "Salario": {"SALARIO BASE": salario_formatado},
        "Premio": {"PREMIO ASSIDUIDADE": premio_assiduidade_formatado, "VALE ALIMENTACAO": vale_alimentacao_formatado,
                   "AUXILIO CRECHE": auxilio_creche_formatado,
                   "AUXILIO FILHO DEFICIENCIA": auxilio_deficiencia_formatado,
                   "PREMIO FUNCAO": premio_funcao_formatado,
                   "PREMIO FORMACAO": premio_formacao_formatado,
                   "TOTAL PREMIACOES": premiacao_total_formatado},
        "Descontos": {"INSS": f'-{descontos_inss_formatado}', "SINDIMETAL": f"-{descontos_sindimetal_formatado}",
                      "TOTAL": f"-{descontos_total_formatado}"},
        "Total": {"TOTAL RECEITAS": receitas_total_formatado, "TOTAL LIQUIDO": total_liquido_formatado}
    }

    # Função para criar uma tabela dbc.Table a partir dos dados

    tabela = html.Div([
        dbc.Row([
            dbc.Col(criar_tabela("Salario", df["Salario"]), width=5),
        ]),
        dbc.Row([
            dbc.Col(criar_tabela("Premio", df["Premio"]), width=5),
        ]),
        dbc.Row([
            dbc.Col(criar_tabela("Descontos", df["Descontos"]), width=5),
        ]),
        dbc.Row([
            dbc.Col(criar_tabela("Total", df["Total"]), width=5),
        ]),
    ])

    return tabela

Try preventing the initial call here:

@callback(
    Output('table', 'children'),
    Input("formacao_academica_simulacao", "value"),
    Input("filho_2_anos_simulacao", "value"),
    Input("filho_deficiencia_simulacao", "value"),
    Input("funcao", "value"), prevent_initial_call=True
)

It didn’t work.

I’m thinking it might be something related to how I organized the page layout, or how each screen loads. Below is my main file, where I configured the routes and the layout. Could you take a look to see if everything is correct here?

import warnings
from dash import Input, Output, html, dcc, dash
import dash_bootstrap_components as dbc
import pandas as pd
import locale
from app import app
import connect
from views import cadastro, simulacao, editar_beneficios, editar_funcao, editar_colaboradores, export_caju, profile, \
    login
from flask_login import current_user, logout_user

# Defina a localidade para o Brasil (pt_BR)
locale.setlocale(locale.LC_ALL, 'pt_BR.UTF-8')
warnings.filterwarnings("ignore")

df_funcao = pd.read_sql_query("SELECT * FROM df_funcao", connect.engine_2)
funcao_aux = df_funcao.to_dict(orient='records')

df_filhos = pd.read_sql_query("SELECT * FROM df_filhos", connect.engine_2)
filhos_colaboradores_aux = df_filhos.to_dict()

df_cadastro = pd.read_sql_query("SELECT * FROM df_cadastro", connect.engine_2)
colaboradores_aux = df_cadastro.to_dict()

df_certificacao = pd.read_sql_query("SELECT * FROM df_certificacao", connect.engine_2)
df_salario = pd.read_sql_query("SELECT * FROM df_salario", connect.engine_2)
df_beneficio = pd.read_sql_query("SELECT * FROM df_beneficio", connect.engine_2)
cadastro_beneficios_aux = df_beneficio.to_dict()

# ========= Layout_sidebar ========= #
layout_sidebar = dbc.Container([
    dbc.Row([
        dbc.Col([
            html.H1("Cadastro de funcionarios", className="text-primary"),
            html.Hr(),
            dbc.Card([
                dbc.CardBody([
                    dbc.Nav(
                        [
                            dbc.NavLink("Cadastro", href="/cadastro", active="exact"),
                            dbc.NavLink("Simulação", href="/simulacao", active="exact"),
                            dbc.NavLink('Beneficios', href='/beneficios', active='exact'),
                            dbc.NavLink('Funções', href='/funcoes', active='exact'),
                            dbc.NavLink('Colaboradores', href='/colaboradores', active='exact'),
                            dbc.NavLink('CAJU', href='/exportar_caju', active='exact'),
                            dbc.NavLink('Configurações', href='/configuracoes', active='exact'),
                        ], vertical=True, pills=True, id='nav_buttons', style={'flex': 1, 'flex-grow': 1}),
                    dbc.Col([
                        dcc.Store(id='codigo_revenda', storage_type='session'),
                        dcc.Store(id='revenda', storage_type='session'),
                        dcc.Location(id='url_atual')
                    ]),

                ]),
            ]),
        ], id='sidebar_completa', style={'padding-top': '10px'})
    ])
], fluid=True)

# =========  Layout Configuracoes  =========== #
layout_configuracoes = html.Div([
    dbc.Row([
        dbc.Col([
            dbc.Card([
                dbc.CardHeader('Configurações'),
                dbc.CardBody([
                    dbc.Row([
                        dbc.Col([
                        ])
                    ]),
                    dbc.Row([
                        dbc.Col([
                        ], style={'margin-top': '10px'})
                    ]),
                    dbc.Row([
                        dbc.Col([
                        ])
                    ])
                ])
            ])
        ], style={'padding-right': '10px', 'padding-top': '10px'}, className='g-0')
    ]),
])

# =========  Layout_total  =========== #
navBar = dbc.Navbar(id='navBar',
                    sticky='top',
                    color='primary',
                    class_name='ml-auto',
                    expand=True)

# Main Layout
app.layout = html.Div([
    dcc.Location(id='url', refresh=False),
    dcc.Location(id='redirect', refresh=True),
    dcc.Store(id='login-status', storage_type='session'),
    html.Div(id='user-status-div'),
    navBar,
    html.Div(id='page-content'),
])

home = html.Div([
    dcc.Store(id='store_colaboradores', data=colaboradores_aux),
    dcc.Store(id='store_colaboradores_nome'),
    dcc.Store(id='store_colaboradores_id'),
    dcc.Store(id='store_colaboradores_id_2'),
    dcc.Store(id='store_funcoes', data=funcao_aux),
    dcc.Store(id='store_funcoes_nome'),
    dcc.Store(id='store_cadastro_beneficios', data=cadastro_beneficios_aux),
    dbc.Container(children=[
        dbc.Row([
            dbc.Col([
                layout_sidebar
            ], width=2, className='g-0'),
            dbc.Col([
                html.Div(id="page-content-2")
            ], width=10),
        ]),
    ], fluid=True)])


@app.callback(Output('navBar', 'children'),
              Output('login-status', 'data'),
              [Input('url', 'pathname')])
def login_status(url):
    ''' callback to display login/logout link in the header '''
    if current_user.is_authenticated:
        navBarContents = [
            dbc.DropdownMenu(
                nav=True,
                in_navbar=True,
                label='Usuário',
                children=[
                    dbc.DropdownMenuItem('Profile', href='/profile'),
                    dbc.DropdownMenuItem(divider=True),
                    dbc.DropdownMenuItem('Logout', href='/logout'),
                ],
                align_end=True,
                style={'margin-left': 'auto', 'margin-right': '20px'}
            )
        ]

        return navBarContents, current_user.get_id()
    else:
        return '', 'loggedout'


# Main router
@app.callback(Output('page-content', 'children'), Output('redirect', 'pathname'),
              [Input('url', 'pathname')])
def display_page(pathname):
    ''' callback to determine layout to return '''
    view = None
    url = dash.no_update
    if pathname == '/login':
        view = login.layout_login
    elif pathname == '/success':
        if current_user.is_authenticated:
            view = home
    elif pathname == '/logout':
        if current_user.is_authenticated:
            logout_user()
            view = login.layout_login
        else:
            view = login.layout_login
            url = '/login'

    elif pathname == '/profile':
        if current_user.is_authenticated:
            view = profile.user
        else:
            view = login.layout_login
            url = '/login'

    else:
        if current_user.is_authenticated:
            view = home
        else:
            view = login.layout_login
            url = '/login'

    # You could also return a 404 "URL not found" page here
    return view, url


@app.callback(Output('page-content-2', 'children'),
              [Input('url', 'pathname')])
def display_page(pathname):
    view = None
    if pathname == "/" or pathname == "/cadastro":
        view = cadastro.layout_cadastro
    elif pathname == '/simulacao':
        if current_user.is_authenticated:
            view = simulacao.layout_simulacao
    elif pathname == '/beneficios':
        if current_user.is_authenticated:
            view = editar_beneficios.layout_beneficios
    elif pathname == '/configuracoes':
        if current_user.is_authenticated:
            view = layout_configuracoes
    elif pathname == '/funcoes':
        if current_user.is_authenticated:
            view = editar_funcao.layout_funcoes
    elif pathname == '/colaboradores':
        if current_user.is_authenticated:
            view = editar_colaboradores.layout_colaboradores
    elif pathname == '/exportar_caju':
        if current_user.is_authenticated:
            view = export_caju.layout_caju

    return view


try:
    import conf

    if __name__ == '__main__':
        app.run_server(debug=True, port=80)
except:
    if __name__ == '__main__':
        app.run_server(debug=False, host='0.0.0.0', port=80)

Try changing the view here to be [] at the top instead of None

1 Like

The solution also didn’t work, but I believe I’ve pinpointed where the problem lies. In my initial post here, I mentioned that the issue worsens when enabling the Flask-Login system. I suspect that I might be configuring this login system incorrectly, and that could be what’s causing all the trouble.

import dash
import dash_bootstrap_components as dbc
import os

import flask
from flask_login import LoginManager, UserMixin
from sqlalchemy.orm import sessionmaker

import connect
from user_mtg import Usuario as base

server = flask.Flask(__name__)

app = dash.Dash(__name__, server=server,
                suppress_callback_exceptions=True,
                external_stylesheets=[dbc.themes.MINTY, dbc.icons.BOOTSTRAP])

# app.config.suppress_callback_exceptions = True

# config
server.config.update(
    SECRET_KEY=os.urandom(12),
    SQLALCHEMY_DATABASE_URI=connect.connstr_2.format(**connect.creds_2),
    SQLALCHEMY_TRACK_MODIFICATIONS=True
)


# Setup the LoginManager for the server
login_manager = LoginManager()
login_manager.init_app(server)
login_manager.login_view = '/login'


class Usuario(UserMixin, base):
    pass


@login_manager.user_loader
def load_user(user_id):
    Session = sessionmaker(bind=connect.engine_2)
    session = Session()

    user = session.query(Usuario).filter_by(
        id=user_id).first()

    session.close()

    return user

# @login_manager.user_loader
# def load_user(username):
#     ''' This function loads the user by user id. Typically this looks up the user from a user database.
#         We won't be registering or looking up users in this example, since we'll just login using LDAP server.
#         So we'll simply return a User object with the passed in username.
#     '''
#     return Usuario()

My app.py file is configured as shown above. The way it’s currently set up (with the simplified final section of the login_manager commented out), the error occurs much more frequently, and on all screens, sometimes preventing them from loading or even breaking the entire application. If I reverse the configurations, i.e., uncomment the final section and comment out what’s currently active, the error is limited to just one screen, and only occasionally.

I noticed that you’ve had experiences with integrating Flask and Dash in the past. Could you take a look to see what I might be doing wrong?

I’m fairly certain that the user you return must be a Usuario, and then set the id as our returned user:

@login_manager.user_loader
def user_loader(username):
    users = build_users()
    if username not in users:
        return

    user = User()
    user.id = username

    return user

Also, if the user is blank you should handle it as well.

Hello, sorry for the delay in responding, I had to deal with other matters.

I didn’t quite understand your solution, but I believe that a good portion of the problem I’m facing is related to my layout, as mentioned before. However, since my application has a certain level of complexity, I’m struggling to find a good way to organize the layout.

# Main Layout
app.layout = html.Div([
    dcc.Location(id='url', refresh=False),
    dcc.Location(id='redirect', refresh=True),
    dcc.Store(id='login-status', storage_type='session'),
    dcc.Store(id='store_login_id', storage_type='session'),
    html.Div(id='user-status-div'),
    navBar,
    html.Div(id='page-content'),
])

home = html.Div([
    dcc.Store(id='store_colaboradores', data=colaboradores_aux),
    dcc.Store(id='store_colaboradores_nome'),
    dcc.Store(id='store_colaboradores_id'),
    dcc.Store(id='store_colaboradores_id_2'),
    dcc.Store(id='store_funcoes', data=funcao_aux),
    dcc.Store(id='store_funcoes_nome'),
    dcc.Store(id='store_cadastro_beneficios', data=cadastro_beneficios_aux),

    dbc.Container(children=[
        dbc.Row([
            dbc.Col([
                layout_sidebar
            ], width=2, className='g-0'),
            dbc.Col([
                html.Div(id="page-content-2")
            ], width=10),
        ]),
    ], fluid=True)])


# Main router
@app.callback(Output('page-content', 'children'), Output('redirect', 'pathname'),
              [Input('url', 'pathname')])
def display_page(pathname):
    ''' callback to determine layout to return '''
    view = None
    url = dash.no_update
    if pathname == '/login':
        if current_user.is_authenticated:
            view = login.layout_login
        else:
            view = login.layout_login
            url = '/login'

    elif pathname == '/logout':
        if current_user.is_authenticated:
            logout_user()
            view = login.layout_login
        else:
            view = login.layout_login
            url = '/login'

    elif pathname == '/profile':
        if current_user.is_authenticated:
            view = profile.user
        else:
            view = login.layout_login
            url = '/login'

    elif pathname == '/admin':
        if current_user.is_authenticated:
            view = user_admin.layout_admin
        else:
            view = login.layout_login
            url = '/login'

    else:
        if current_user.is_authenticated:
            view = home
        else:
            view = login.layout_login
            url = '/login'

    # You could also return a 404 "URL not found" page here
    return view, url


@app.callback(Output('page-content-2', 'children'),
              [Input('url', 'pathname')])
def display_page_2(pathname):
    view = []
    if pathname == "/" or pathname == "/cadastro":
        view = cadastro.layout_cadastro
    elif pathname == '/simulacao':
        if current_user.is_authenticated:
            view = simulacao.layout_simulacao
    elif pathname == '/beneficios':
        if current_user.is_authenticated:
            view = editar_beneficios.layout_beneficios
    elif pathname == '/configuracoes':
        if current_user.is_authenticated:
            view = layout_configuracoes
    elif pathname == '/funcoes':
        if current_user.is_authenticated:
            view = editar_funcao.layout_funcoes
    elif pathname == '/colaboradores':
        if current_user.is_authenticated:
            view = editar_colaboradores.layout_colaboradores
    elif pathname == '/exportar_caju':
        if current_user.is_authenticated:
            view = export_caju.layout_caju

    return view

I believe the way I’ve configured it is wrong. My application is basically composed of 2 different layouts: one is used for the login screen, admin, and profile, and the other is used in conjunction with another sidebar screen to navigate through the application. However, it’s noticeable that the layout isn’t responsive. Do you have any tips on how I can improve this layout?

My recommendation would be to cater the /login and /logout pages from flask templates. And have the layout be a function that checks if the user is logged in, if not, then have them redirect to the login screen.

If logged in, the you can have your home layout catered.

I liked the idea. Then I can put the admin and profile screens within the same layout as the other pages. But how do I create the /login and /logout pages in the Flask template? I don’t have much experience with the Flask library yet.

Oh, its really simple.

Just the rawr html as your login.

What login auth are you using?

I use the LoginManager from flask_login

You can check out the document here for some examples: