Django向Google Charts传递数据时图表不显示问题求助
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:
Solution 1: Use Django's json_script Filter (Recommended)
This method is secure and handles all syntax conversion automatically, including XSS protection.
- Add the JSON data tag to your template (place this anywhere before your
<script>block):
{{ data|json_script:"chart-data" }}
- 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:
- Modify your
views.pyto 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})
- 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

