无法在Django和Chart.js之间传递数据。

huangapple go评论100阅读模式
英文:

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

  1. return render(request, 'notes/home.html',{
  2. 'day': daysOfMonth,
  3. })
  1. <div class="mainChart">
  2. <canvas id="myChart"></canvas>
  3. <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  4. <script>
  5. const ctx = document.getElementById('myChart');
  6. const days = '{{day}}';
  7. new Chart(ctx, {
  8. type: 'bar',
  9. data: {
  10. labels: days,
  11. datasets: [{
  12. // label: '# of Votes',
  13. 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,],
  14. borderWidth: 10
  15. }]
  16. },
  17. options: {
  18. scales: {
  19. y: {
  20. beginAtZero: true
  21. }
  22. }
  23. }
  24. });
  25. </script>
  26. </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

  1. return render(request, &#39;notes/home.html&#39;,{
  2. &#39;day&#39;:daysOfMonth,
  3. })
  1. &lt;div class=&quot;mainChart&quot;&gt;
  2. &lt;canvas id=&quot;myChart&quot;&gt;&lt;/canvas&gt;
  3. &lt;script src=&quot;https://cdn.jsdelivr.net/npm/chart.js&quot;&gt;&lt;/script&gt;
  4. &lt;script&gt;
  5. const ctx = document.getElementById(&#39;myChart&#39;);
  6. const days = &#39;{{day}}&#39;;
  7. new Chart(ctx, {
  8. type: &#39;bar&#39;,
  9. data: {
  10. labels: days,
  11. datasets: [{
  12. // label: &#39;# of Votes&#39;,
  13. 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,],
  14. borderWidth: 10
  15. }]
  16. },
  17. options: {
  18. scales: {
  19. y: {
  20. beginAtZero: true
  21. }
  22. }
  23. }
  24. });
  25. &lt;/script&gt;
  26. &lt;/div&gt;

答案1

得分: 0

Sure, here's the translated content:

更改上下文数据如下

  1. 'day': json.dumps(daysOfMonth)

并且模板更改如下

  1. var days = JSON.parse('{{day|safe}}');
英文:

Change the context data like this

  1. &#39;day&#39;:json.dumps(daysOfMonth)

and is the template change is to this

  1. var days = JSON.parse(&#39;{{day|safe}}&#39;);

huangapple
  • 本文由 发表于 2023年6月4日 23:20:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76401091.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定