在用django寫一個可視化圖表echart時,需要從視圖函數向模板中的javascript傳遞生成圖表的列表數據,方法如下:
1. view.py
def chinachart(request):
pclist_types=pc_list.objects.filter(site_list_id=1,pcstatustable_id__in=(1,2,3,5),motable__hosttype_list__in=(1,2,3,12)).values('motable__hosttype_list__name').annotate(name=F('motable__hosttype_list__name') ,total=Count('motable__hosttype_list__name')).order_by('motable__hosttype_list__id')
x = [i['name'] for i in pclist_types]
y = [i['total'] for i in pclist_types]
x = json.dumps(x)
y = json.dumps(y)
return render(request,'deviceman/chartjs.html',{'x':x,'y':y})
將列表傳遞給模板中的javascript變量label, data,
2. chart.html
$(function () {
/* ChartJS
* -------
* Here we will create a few charts using ChartJS
*/
//--------------
//- AREA CHART -
//--------------
// Get context with jQuery - using jQuery's .get() method.
var areaChartCanvas = $('#areaChart').get(0).getContext('2d')
var areaChartData = {
//labels : ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
labels : {{ x|safe}},
datasets: [
{
label : '',
backgroundColor : 'rgba(60,141,188,0.9)',
borderColor : 'rgba(60,141,188,0.8)',
pointRadius : false,
pointColor : '#3b8bba',
pointStrokeColor : 'rgba(60,141,188,1)',
pointHighlightFill : '#fff',
pointHighlightStroke: 'rgba(60,141,188,1)',
//data : [28, 48, 40, 19, 86, 27, 90]
data : []
},
{
label : 'CNSHZ1',
backgroundColor : 'rgba(210, 214, 222, 1)',
borderColor : 'rgba(210, 214, 222, 1)',
pointRadius : false,
pointColor : 'rgba(210, 214, 222, 1)',
pointStrokeColor : '#c1c7dd',
pointHighlightFill : '#fff',
pointHighlightStroke: 'rgba(220,220,220,1)',
//data : [65, 59, 80, 81, 56, 55, 40]
data : {{ y|safe }}
},
]
}
3. 以下是效果圖