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

Django向Google Charts传递数据时图表不显示问题求助

Fixing Google Charts Not Rendering with Django-Passed Data

Hey there, I see the issue you're running into—let's break this down and fix it quickly!

The problem is that when you use {{ data }} directly in your JavaScript, Django renders the Python list as a string with single quotes and Python-style formatting, which doesn't match JavaScript's expected array syntax. Google Charts' arrayToDataTable can't parse this messy string into a valid data structure, which is why your chart works with hardcoded data but not when passing it from Django.

Here are two solid solutions, starting with the safest and most recommended one:

This method is secure and handles all syntax conversion automatically, including XSS protection.

  1. Add the JSON data tag to your template (place this anywhere before your <script> block):
{{ data|json_script:"chart-data" }}
  1. Update your JavaScript code to parse the properly formatted JSON:
<script type="text/javascript">
google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawBasic);
function drawBasic() {
    // Parse the JSON data from the hidden script tag
    var chartData = JSON.parse(document.getElementById('chart-data').textContent);
    var data2 = google.visualization.arrayToDataTable(chartData);
    
    var options = {
        chartArea: { left: 50, top: 5, right: 5, bottom: 50, width: 500, height: 300 },
        hAxis: { title: 'Average Interactions', minValue: 0 },
    };
    
    var days = new google.visualization.BarChart(document.getElementById('days_div'));
    days.draw(data2, options);
}
</script>

Solution 2: Pre-convert Data to JSON in Views

If you prefer handling the conversion server-side, you can use Python's json module:

  1. Modify your views.py to convert the list to a JSON string:
import json
from django.shortcuts import render

def home(request):
    posts = [['day', 'ic'], ['Fri', 3601326.0], ['Mon', 1450340.0], ['Sat', 2094946.0], ['Sun', 2373750.0], ['Thu', 3116066.0], ['Tue', 729403.0], ['Wed', 1934780.0]]
    # Convert the Python list to a JSON string
    json_posts = json.dumps(posts)
    return render(request, 'kodey/home.html', {'data': json_posts})
  1. Update your template's JavaScript to use the safe JSON string:
<script type="text/javascript">
google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawBasic);
function drawBasic() {
    // Use |safe to prevent Django from escaping the JSON syntax
    var data2 = google.visualization.arrayToDataTable( {{ data|safe }} );
    
    var options = {
        chartArea: { left: 50, top: 5, right: 5, bottom: 50, width: 500, height: 300 },
        hAxis: { title: 'Average Interactions', minValue: 0 },
    };
    
    var days = new google.visualization.BarChart(document.getElementById('days_div'));
    days.draw(data2, options);
}
</script>

Quick Check

Don't forget to make sure your HTML has the target element for the chart:

<div id="days_div"></div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 15:02:33