Django和ChartJS [英] Django and ChartJS

查看:78
本文介绍了Django和ChartJS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解是否可以将动态数据合并到Django Chart JS体系结构中。我完成了一些教程,最终使Django与ChartJS一起使用,当我能够对值进行硬编码然后显示相关图形时,这非常好。我最终想要做的就是对数据库中的动态数据进行同样的练习。我在 https:// stackoverflow中找到了相同的问题。 com / questions / 47575896 / dynamic-chart-using-django-and-chart-js# = ,但没有任何人回答。这正是我要实现的目标。我已经研究了序列化器,我需要先序列化数据吗?预先感谢您的想法和反馈。

I'm trying to understand if it it's possible to incorporate dynamic data into a Django Chart JS architecture. I went through a couple of tutorials and ultimately got Django to work with ChartJS and it's very good when I'm able to hard code values and then display the related graphs. What I'm ultimately trying to do is this same exercise with dynamic data from my database. I found this identical question in SO, https://stackoverflow.com/questions/47575896/dynamic-chart-using-django-and-chart-js#= but it wasn't answered by anyone. This is exactly what I'm trying to achieve. I've explore serializers a bit, do I need to serialize the data first? Thanks in advance for your thoughts and feedback.

根据反馈,我向有问题的图表添加了上下文,但是数据仍然无法传递。这是我的观点:

Per the feedback, I have added context to the chart in question but the data is still not coming through. Here is my view:

class ChartView(LoginRequiredMixin, TemplateView):

    model = Myobject 
    template_name = 'director/chart.html'

      def get_context_data(self, **kwargs):
          context = super(ChartView, self).get_context_data(**kwargs)  
          myobject = Myobject.objects.filter(field__in=self.request.user.userprofile.field.all())
          print(myobject)
          context['myobject'] = myobject
          return context

我只是得到一个空白屏幕,根本没有图表,这表明显然不对劲。我是否需要对Javascript进行其他更改以告知它有关该对象的信息?我的假设不是,我正在传递此信息以查看context_data。

I'm just getting a blank screen, no chart at all, suggesting that something is obviously amiss. Do I need to make additional changes to the Javascript in order to tell it about the object? My assumption is no, that I'm passing this information view the context_data.

我也在使用Ajax,所以我不确定这是否是一个复杂的因素。这是我的JavaScript。

I'm also using Ajax, so I'm not sure if that is a complicating factor. Here is my javascript.

<script>
var endpoint = '{% url "myobject:chart_data" %}'
var defaultData = [];
var labels = [];
$.ajax({
    method: "GET",
    credentials: 'same-origin',
    url: endpoint,
    success: function(data){
        labels = data.labels
        defaultData = data.default
        var ctx = document.getElementById("myChart");
        var myChart = new Chart(ctx, {
            type: 'pie',
            data: {
                labels: [{% for i in myobject %}{{ i.labels }},{% endfor %}],
                datasets: [{
                    data: [{% for i in myobject %}{{ i.data }},{% endfor %}]
                    backgroundColor: [
                        'rgba(255, 99, 132, 0.2)',
                        'rgba(153, 102, 255, 0.2)',
                    ],
                    borderColor: [
                        'rgba(255,99,132,1)',
                        'rgba(153, 102, 255, 1)',
                    ],
                    borderWidth: 1
                }]
            }
        })
    },
    error: function(error_data){
        console.log("error")
        console.log(error_data)
    }
})
</script>


推荐答案

您不一定需要使用序列化程序进行渲染Chart.js中的动态数据(尽管您可以根据需要)。您可以在适当的位置像平常一样遍历Django上下文变量。下面是一个折线图示例。我将使用这个示例,但这将向您展示如何使用Django上下文变量轻松呈现动态数据。

You don't necessarily need to use serializers to render dynamic data in Chart.js (although you can if you would like). You can just iterate through your Django context variables like normal in the appropriate locations. Below is a line chart example. I would play around with this example, but this should show you how to easily render dynamic data with Django context variables.

...
<canvas id="funchart" width="75" height="50"></canvas>                      

<script type="text/javascript">  
     var a = document.getElementById('funchart').getContext('2d');
     var myLineChart = new Chart(a, {
               type: 'line',
               data: {
                   labels:[{% for i in myobject %}{{ i.labels }},{% endfor %}],
                   datasets: [{
                        label:'My Dot',
                        data: [{% for i in myobject %}{{ i.data }},{% endfor %}]
                             }]
                      },
               options:{
                   scales: {
                       xAxes: [{
                           display:true
                              }],
                       yAxes: [{
                           ticks: {
                               beginAtZero:true
                                   }
                               }]
                            }
                        }
                      });
</script>

这篇关于Django和ChartJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆