Django向Chart.js传递日期数组显示异常问题求助
问题:Django传递日期数组到Chart.js显示异常
尝试将当月日期数组(如[1,2,3……])从Django传递到Chart.js做图表展示,数据已传递但图表显示异常,呈现[ 0 1 3 5 7 9 0 ……],但控制台打印数据正常。
后端Django代码
return render(request, 'notes/home.html',{ 'day':daysOfMonth, })
前端代码
<div class="mainChart"> <canvas id="myChart"></canvas> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <script> const ctx = document.getElementById('myChart'); const days = '{{day}}'; new Chart(ctx, { type: 'bar', data: { labels: days, datasets: [{ // label: '# of Votes', data: [1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10], borderWidth: 10 }] }, options: { scales: { y: { beginAtZero: true } } } }); </script> </div>
问题原因
将Django传递的数组用{{day}}包裹在字符串引号中,导致它变成了字符串形式的数组,而非JavaScript可识别的数组对象。Chart.js解析该字符串时,会将其当作单个长字符串拆分处理,从而出现乱序数字的异常显示。
解决方法
需要把Django的数组转换为合法的JavaScript数组,而非字符串,以下是两种常用方案:
方案1:使用json_script模板标签(推荐)
Django内置的json_script标签可安全地将Python序列转换为JavaScript可识别的JSON:
- 后端代码保持不变
- 前端修改如下:
<div class="mainChart"> <canvas id="myChart"></canvas> <!-- 添加该标签,将day序列化为JSON --> {{ day|json_script:"days-data" }} <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <script> const ctx = document.getElementById('myChart'); // 读取JSON数据并转为JS数组 const days = JSON.parse(document.getElementById('days-data').textContent); new Chart(ctx, { type: 'bar', data: { labels: days, datasets: [{ // label: '# of Votes', data: [1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10], borderWidth: 10 }] }, options: { scales: { y: { beginAtZero: true } } } }); </script> </div>
方案2:直接输出数组(简单但需注意安全)
如果数组仅包含数字这类安全内容,可直接去掉引号,让Django输出的数组直接成为JavaScript数组:
// 去掉引号,直接使用{{day}} const days = {{ day }};
该方案的缺点是:若数组包含字符串或特殊字符,可能引发JavaScript语法错误,因此优先推荐方案1。
内容的提问来源于stack exchange,提问作者Mt Khalifa
相关产品推荐
相关产品推荐

