You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Docker Compose栈集成django-plotly-dash遇MIME类型错误求助

Django集成Dash时MIME类型错误的解决方法

在Nginx、Django和Postgres组成的Docker Compose栈中集成Dash时,浏览器控制台出现如下错误:

Refused to execute script from 'http://localhost:8008/trendyqc/django_plotly_dash/app/Plot/_dash-component-suites/plotly/package_data/plotly.min.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.

当前滑块组件可正常工作,但图表无法显示。

环境配置信息

Settings.py 配置

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "trend_monitoring",
    "django_bootstrap5",
    "django_plotly_dash.apps.DjangoPlotlyDashConfig",
    "dpd_static_support",
]

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
    "debug_toolbar.middleware.DebugToolbarMiddleware",
    "django_plotly_dash.middleware.BaseMiddleware",
    "django_plotly_dash.middleware.ExternalRedirectionMiddleware",
]

X_FRAME_OPTIONS = "SAMEORIGIN"

STATICFILES_FINDERS = [
    "django.contrib.staticfiles.finders.FileSystemFinder",
    "django.contrib.staticfiles.finders.AppDirectoriesFinder",
    "django_plotly_dash.finders.DashAssetFinder",
    "django_plotly_dash.finders.DashComponentFinder",
    "django_plotly_dash.finders.DashAppDirectoryFinder",
]
PLOTLY_COMPONENTS = [
    # Common components (ie within dash itself) are automatically added
    # django-plotly-dash components
    "dpd_components",
    # static support if serving local assets
    "dpd_static_support",
    # Other components, as needed
    "dash_bootstrap_components",
]

Dash应用代码

from dash import dcc, html, Input, Output, callback
import dash_bootstrap_components as dbc
from django_plotly_dash import DjangoDash
import plotly.express as px

import pandas as pd

df = pd.read_csv(
    "https://raw.githubusercontent.com/plotly/datasets/master/gapminderDataFiveYear.csv"
)

app = DjangoDash(
    "Plot",
    external_stylesheets=[dbc.themes.BOOTSTRAP],
    add_bootstrap_links=True,
)

app.layout = html.Div(
    [
        dcc.Graph(id="graph-with-slider"),
        dcc.Slider(
            df["year"].min(),
            df["year"].max(),
            step=None,
            value=df["year"].min(),
            marks={str(year): str(year) for year in df["year"].unique()},
            id="year-slider",
        ),
    ]
)


@callback(Output("graph-with-slider", "figure"), Input("year-slider", "value"))
def update_figure(selected_year):
    filtered_df = df[df.year == selected_year]

    fig = px.scatter(
        filtered_df,
        x="gdpPercap",
        y="lifeExp",
        size="pop",
        color="continent",
        hover_name="country",
        log_x=True,
        size_max=55,
    )

    fig.update_layout(transition_duration=500)

    return fig

依赖版本

Django==6.0.4
django-bootstrap5==26.2
django-plotly-dash==2.5.0
dpd-static-support==0.0.5

解决步骤

1. 确保静态文件正确收集

在Docker容器内执行静态文件收集命令,确保Dash的组件资源被同步到STATIC_ROOT目录:

python manage.py collectstatic --noinput

Docker环境下建议在构建镜像时加入该命令,或者在容器启动脚本中执行,避免每次启动重复操作。

2. 完善静态文件配置

在settings.py中确认静态文件相关配置:

STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR / 'staticfiles'  # 确保路径正确指向静态文件目录

# 部署环境下需关闭DEBUG模式
DEBUG = False

同时确保Nginx配置中正确映射了静态文件路径,比如:

location /static/ {
    alias /path/to/staticfiles/;
}

3. 检查路由配置

确认项目的urls.py中包含django-plotly-dash的路由:

from django.urls import include, path

urlpatterns = [
    # 其他路由配置
    path('django_plotly_dash/', include('django_plotly_dash.urls')),
]

如果项目使用了URL前缀(如示例中的trendyqc/),需确保路由前缀与请求路径匹配,或者在DjangoDash初始化时指定正确的namespace参数。

4. 调整版本兼容性

Django 6.0.x属于较新版本,而django-plotly-dash 2.5.0发布于2023年,可能尚未适配Django 6.x。建议降级Django到5.x版本(如5.0.7),重新安装依赖后测试:

pip install Django==5.0.7

5. 验证dpd_static_support配置

确认INSTALLED_APPS中已包含dpd_static_support,且STATICFILES_FINDERS中的Dash相关Finder配置正确,这一步你的配置已经满足,但需确保collectstatic时这些资源被正确收集。

内容的提问来源于stack exchange,提问作者Yujin Kim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.01 19:24:50