django view向模板javascript傳遞列表,生成可視化圖表chart

在用django寫一個可視化圖表echart時,需要從試圖函數向模板傳遞列表數據,方法如下:
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})

 

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. 以下是效果圖

t

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章