在Django中托管Dash应用遇routes_pathname_prefix配置错误
解决Django托管Dash应用时
routes_pathname_prefix开头错误的问题 1. 修正DjangoDash实例的路径配置
错误核心是Dash应用的路由前缀未正确设置,导致url_base_pathname异常带上https。修改Dash实例初始化代码,显式指定符合要求的路径参数:
app = DjangoDash( name='SimpleExample', routes_pathname_prefix='/django_plotly_dash/app/SimpleExample/', url_base_pathname='/django_plotly_dash/app/SimpleExample/' )
routes_pathname_prefix必须以/开头,对应Dash内部路由的前缀url_base_pathname要和Django中django_plotly_dash的URL前缀匹配,保证路径一致性
2. 修正URL配置中的静态文件参数
你的URL配置里static(settings.STATIC_SUFFIX, ...)存在错误,应替换为settings.STATIC_URL:
urlpatterns= [ path("", include('preprocess_train_data.urls')), path("", include('prediction.urls')), path("django_plotly_dash/", include('django_plotly_dash.urls')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
该错误可能导致静态资源加载异常,间接引发Dash路径解析错误。
3. 简化模板中的Dash调用
模板中无需手动引入Plotly的CDN脚本,django_plotly_dash会自动处理相关资源加载,移除多余标签并修正HTML结构:
{% extends 'home.html' %} {% block content %} {% load plotly_dash %} <div class="{% plotly_class name="SimpleExample" %} card" style="height: 100%; width: 100%;"> {% plotly_app name="SimpleExample" %} </div> {{ script|safe }} {% endblock content %}
4. 验证Channels路由配置(可选)
若使用ASGI和Channels,确保core.routing.application包含django_plotly_dash的WebSocket路由:
# core/routing.py from django.urls import re_path, include from channels.routing import ProtocolTypeRouter, URLRouter import django_plotly_dash.routing application = ProtocolTypeRouter({ "http": URLRouter([ re_path(r'^django_plotly_dash/', include('django_plotly_dash.urls')), # 其他Django URL路由 ]), "websocket": URLRouter([ re_path(r'^django_plotly_dash/ws/', include('django_plotly_dash.routing.websocket_urlpatterns')), ]), })
WebSocket路由缺失可能导致Dash回调失效,也可能间接引发路径相关错误。
完成以上修改后重启Django服务,即可解决routes_pathname_prefix的开头错误问题。
内容的提问来源于stack exchange,提问作者Codein
相关产品推荐
相关产品推荐

