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

如何在网页中嵌入多个Plotly图表?Django实现求助

Django实现Plotly图表网格布局的代码修正

原代码存在的问题

  1. views.py:fig.write_html()返回值为None,导致hlist全是空值,无法传递有效内容到模板;生成单独HTML文件再用iframe加载的方式冗余,不利于布局控制。
  2. index.html:循环时错误引用plotly_div而非当前循环项x;现有样式为垂直排列,未实现网格布局;autoescape被注释,直接渲染Plotly的div字符串会被转义。

修正后的代码实现

views.py

import plotly.express as px
from django.shortcuts import render

def plot_view(request):
    # 假设df是从数据库获取并预处理完成的DataFrame
    unique_m = df['metric'].unique()
    plot_divs = []
    for m in unique_m:
        df2 = df.loc[df['metric'] == m]
        fig = px.line(df2, x="date", y="value", title=m, width=700, height=500)
        # 直接生成Plotly的div字符串,无需保存独立HTML文件
        plot_html = fig.to_html(full_html=False, include_plotlyjs='cdn')
        plot_divs.append(plot_html)
    
    context = {'plot_divs': plot_divs}
    return render(request, 'index.html', context)

index.html

{% extends "base.html" %}
{% block content %}
    <!-- 用CSS Grid实现响应式网格布局 -->
    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(700px, 1fr)); gap: 20px; padding: 20px;">
        {% autoescape off %}
            {% for div in plot_divs %}
                <div>{{ div }}</div>
            {% endfor %}
        {% endautoescape %}
    </div>
{% endblock content %}

关键说明

  • 移除iframe冗余:直接传递Plotly生成的div字符串,减少文件IO操作,同时让布局调整更灵活。
  • 响应式网格:CSS Grid的auto-fit+minmax组合,让图表在不同屏幕尺寸下自动适配列数,实现自适应网格布局。
  • 关闭自动转义:{% autoescape off %}确保Plotly的HTML代码被正确渲染,不会被Django转义为纯文本。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 03:07:38