如何解决Django多个chartJs在页面中聊天 Barchart1.html Barchart2.html Barchart3.html
我正在开发仪表板。我有3个html页面,其中包含如下图所示的图表。我有3个图表,因为我将在整个django项目中使用其他html页面中的图表。因此,我决定将图表放在不同的html页面中,并从视图中提供数据。
Barchart1.html
"Room:["
Barchart2.html
<canvas id="myChart" width="400" height="400"></canvas>
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx,{
type: 'bar',data: {
labels: ['Red','Blue','Yellow','Green','Purple','Orange'],datasets: [{
label: '# of Votes',data: [12,19,3,5,2,3],backgroundColor: [
'rgba(255,99,132,0.2)','rgba(54,162,235,'rgba(255,206,86,'rgba(75,192,'rgba(153,102,255,159,64,0.2)'
],borderColor: [
'rgba(255,1)',1)'
],borderWidth: 1
}]
},options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
</script>
Barchart3.html
<canvas id="myChart" width="400" height="400"></canvas>
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx,options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
</script>
我希望这些图表显示在master.html页面中,并将提供来自词典的数据。有可能吗,我该怎么办。
解决方法
首先,您需要从视图中返回字典。像这样。
votes_dict={'one':12,'two': 19,'three': 3,'four': 5,'five': 2,'six': 3}
return render(request,'master.html',{'votes':votes_dict})
因此,voices_dict是您的词典,而投票只是您将要使用的名称,因此您可以在模板上引用它。
然后在您的模板上看起来像这样...
{% block content %}
{% if votes %}
<canvas id="myChart" width="400" height="400"></canvas>
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx,{
type: 'bar',data: {
labels: ['Red','Blue','Yellow','Green','Purple','Orange'],datasets: [{
label: '# of Votes',data: [{{ votes.one }},{{ votes.two }},{{ votes.three }},{{ votes.four }},{{ votes.five }},{{ votes.six }} ],backgroundColor: [
'rgba(255,99,132,0.2)','rgba(54,162,235,'rgba(255,206,86,'rgba(75,192,'rgba(153,102,255,159,64,0.2)'
],borderColor: [
'rgba(255,1)',1)'
],borderWidth: 1
}]
},options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
</script>
{% endif %}
如果字典大于一维,它将看起来像这样
{% for vote in votes %}
{{ vote.one }},{{ vote.two }},{{ vote.three }},{{ vote.four }},{{ vote.five }},{{ vote.six }}
{% endfor %}
{% endif %}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。