英文:
cant pass data between Django and Chartjs
问题
I wanted to pass an array to chartjs for a chart the data is getting passed but for some strange reason the data gets changed, the array contains days of the month [1,2,3,so on] but on chart it displays "[ 0 1 3 5 7 9 0 so on ]"
the data is good when I print it to console
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>
英文:
I wanted to pass an array to chartjs for a chart the data is getting passed but for some strange reason the data gets changed, the array contains days of the month [1,2,3,so on] but on chart it displays "[ 0 1 3 5 7 9 0 so on ]"
the data is good when I print it to console
    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>
答案1
得分: 0
Sure, here's the translated content:
更改上下文数据如下
'day': json.dumps(daysOfMonth)
并且模板更改如下
var days = JSON.parse('{{day|safe}}');
英文:
Change the context data like this
'day':json.dumps(daysOfMonth)
and is the template change is to this
 var days = JSON.parse('{{day|safe}}');
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论