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

Django Python中如何遍历元组列表数据生成Chart.js图表

Django 遍历元组结构数据生成图表的实现方案

方案1:前端Chart.js渲染(匹配你提供的代码效果)

后端处理(views.py)

首先处理[('A', 1),('B', 2),('C', 4)]格式的原始数据,拆分标签和数值后传递给模板:

import json
from django.shortcuts import render

def chart_view(request):
    # 你的原始数据,可从数据库/接口动态获取
    stat_data = [('A', 1), ('B', 2), ('C', 4)]
    # 遍历拆分标签和数值
    labels = [item[0] for item in stat_data]
    data_values = [item[1] for item in stat_data]
    # 转成JSON字符串传递给模板,避免JS解析报错
    context = {
        "labels": json.dumps(labels),
        "data_values": json.dumps(data_values)
    }
    return render(request, "chart.html", context)

模板实现(chart.html)

在模板中插入canvas容器,替换原有JS代码中的labels和data字段即可:

<!-- 自行引入Chart.js依赖 -->
<canvas id="myChart" width="400" height="200"></canvas>
<script>
const ctx = document.getElementById('myChart').getContext('2d');
// 解析后端传递的JSON数据
const labels = JSON.parse('{{ labels|safe }}');
const dataValues = JSON.parse('{{ data_values|safe }}');

var myChart = new Chart(ctx, {
type: 'bar',
data: {
    labels: labels,
    datasets: [{
        label: '# of Votes',
        data: dataValues,
        backgroundColor: [
            'rgba(255, 99, 132, 0.2)',
            'rgba(54, 162, 235, 0.2)',
            'rgba(255, 206, 86, 0.2)',
            'rgba(75, 192, 192, 0.2)',
            'rgba(153, 102, 255, 0.2)',
            'rgba(255, 159, 64, 0.2)'
        ],
        borderColor: [
            'rgba(255, 99, 132, 1)',
            'rgba(54, 162, 235, 1)',
            'rgba(255, 206, 86, 1)',
            'rgba(75, 192, 192, 1)',
            'rgba(153, 102, 255, 1)',
            'rgba(255, 159, 64, 1)'
        ],
        borderWidth: 2
    }]
},
options: {
    scales: {
        y: {
            beginAtZero: true
        }
    }
}
});
</script>

方案2:后端生成静态图表(无前端JS依赖)

适合不需要交互的场景,用matplotlib直接生成图片返回:

import matplotlib.pyplot as plt
from io import BytesIO
from django.http import HttpResponse

def static_chart_view(request):
    stat_data = [('A', 1), ('B', 2), ('C', 4)]
    labels = [item[0] for item in stat_data]
    values = [item[1] for item in stat_data]
    
    # 绘图
    plt.bar(labels, values)
    plt.ylabel('数值')
    plt.xlabel('标签')
    
    # 转成字节流返回
    buffer = BytesIO()
    plt.savefig(buffer, format='png')
    buffer.seek(0)
    return HttpResponse(buffer, content_type='image/png')

方案3:纯HTML/CSS简易图表(零依赖)

适合轻量展示场景,直接在模板遍历渲染:

<style>
.chart-item { margin: 10px 0; display: flex; align-items: center; gap: 10px; width: 300px; }
.chart-label { width: 20px; }
.chart-bar { height: 20px; background: rgba(54, 162, 235, 0.6); border: 1px solid rgba(54, 162, 235, 1); }
</style>

{% with max_value=4 %} <!-- 可通过后端计算最大值动态传递 -->
{% for label, value in stat_data %}
<div class="chart-item">
    <span class="chart-label">{{ label }}</span>
    <div class="chart-bar" style="width: {% widthratio value max_value 100 %}%"></div>
    <span>{{ value }}</span>
</div>
{% endfor %}
{% endwith %}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 14:24:08