1. 程式人生 > >django中使用chart.js的例子

django中使用chart.js的例子

背景:由於運營的需求,需要一些資料圖表進行分析。整個思路是這樣的,利用DJANGO的ORM操作資料庫,從庫中查詢出所需要的資料。並把查詢整個動作封裝成一個數據介面。返回給前端json格式。利用chart.js將資料展現在頁面上。

html

引用好所需要的檔案,static可以在settings.py中設定好。

<script src="{% static "js/Chart.js" %}"></script>
<script src="{% static "js/Chart.min.js" %}"></script>
<div class
="col-sm-4">
<h3>使用者操作錯誤記錄種類</h3> <canvas id="myChart" width="400" height="400"></canvas> </div>

這裡套用了一些bootstrap的內容其實只需要一句

<canvas id="myChart" width="400" height="400"></canvas>

js

    var k,s;
    /*獲取圖表資料*/
    var getdata = BASE_URL + '/operation/all'
; $.get(getdata, function(data){ console.log((data)); k = data.labels; s = data.data; var ctx = $("#myChart").get(0).getContext("2d"); //This will get the first returned node in the jQuery collection. var myNewChart = new Chart(ctx); Chart.defaults.
global.responsive = true; var data = { labels : k, datasets : [ { label: "My Second dataset", fillColor: "rgba(151,187,205,0.5)", strokeColor: "rgba(151,187,205,0.8)", highlightFill: "rgba(151,187,205,0.75)", highlightStroke: "rgba(151,187,205,1)", data: s } ] } new Chart(ctx).Bar(data); });

view.py

class CustomerShowdata(View):
    """
    圖表詳情頁面
    """
    template = "customer/showdata.html"


    @method_decorator(login_required)
    def get(self, request, *args, **kwargs):
        page_name = "customer_show_data"


        return render_to_response(self.template,
                                  context_instance=RequestContext(request, locals()))

APIView

編寫符合REST設計原則的介面.其實上面的VIEW不需要,因為直接在JS端呼叫了這個API.只是我重新寫了一個頁面,網頁訪問需要上面的VIEW來回應HtttpResponse

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated

class GetOperationFail(APIView):
    """
    獲取所有使用者的操作錯誤資訊列表
    """

    permission_classes = (IsAuthenticated, )

    def get(self, request, *args, **kwargs):

        ins = ConsoleRecord()
        data_map = ins.get_fail_data()
        tags=[]
        numbers=[]
        for key,value in data_map.iteritems():
            tags.append(key)
            numbers.append(value)

        return Response({"labels" : tags,
                         "data" : numbers,

        })

model部分

class ConsoleRecord(models.Model):
    """
    Record user actions
    """

    class Meta:
        db_table = "records"

    # 使用者名稱
    username = models.CharField(
        max_length=30,
        null=False
    )

    name = models.CharField(
        max_length=30,
        null=False
    )
    # 操作時間
    create_datetime = models.DateTimeField(
        auto_now_add=True
    )


    # 資源
    service = models.CharField(
        choices=SERVICE_CHOICES,
        max_length=30
    )

    # 操作
    action = models.CharField(
        max_length=30,
        null=False,
    )



    # 狀態
    status = models.CharField(
        max_length=100,
        null=False
    )


    def __unicode__(self):
        return "%s %s %s %s" % (self.username,
                                self.action,
                                self.service,
                                self.create_datetime
                                )

    @classmethod
    def create(cls,
               service,
               action,
               action_detail,
               status,
               ):
        try:
            _console_record = ConsoleRecord(

                service=service,
                action=action,
                action_detail=action_detail,
                status=status,

            )
            _console_record.save()
            return _console_record, None
        except Exception as exp:
            return None, str(exp)


    @classmethod #返回大類錯誤資訊
    def get_fail_data(cls):

        allfail = cls.objects.filter(status=u'失敗')
        logger.debug(allfail)
        data_map = {}
        tags = []
        numbers = []
        for everyone in allfail:
            # data_js = json.dumps()
            word = everyone.service
            if word in data_map:

                data_map[word] += 1
            else:
                data_map[word] = 1
        return data_map

    #傳入需要的資源的值,返回詳細的錯誤資訊。 eg: get_fail_data_details(_('service'))
    @classmethod
    def get_fail_data_details(cls,value):
        date_map = {}
        allfail = cls.objects.filter(status=u'失敗',service=value)
        logger.debug(allfail)
        data_map = {}
        for everyone in allfail:
            # data_js = json.dumps()
            word = everyone.action
            if word in data_map:
                data_map[word] += 1
            else:
                data_map[word] = 1
        return data_map