Django和Chart.js无法正确渲染图形 [英] Django and Chart.js Not Rendering Graph Correctly

查看:56
本文介绍了Django和Chart.js无法正确渲染图形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我花了整个周末进行测试和搜索,最终使Django和Chart.js正常工作.有点儿.它呈现图形,但数据不正确.当我遍历对象时,结果不是我期望的.也许我整个周末都无法注视.将不胜感激任何指针.

So I spent the weekend testing and searching SO and finally got Django and Chart.js working. Kind of. It renders the graph but the data is not correct. When I loop through the object, the results are not what I would expect. Maybe I'm blind from staring at this all weekend. Would appreciate any pointers.

这是我的观点...

class ChartView(LoginRequiredMixin, TemplateView):
    template_name = 'Books/chart.html'

    def get_context_data(self, **kwargs):
        context = super(ChartView, self).get_context_data(**kwargs)
        qs1 = Class.objects.filter(id__in=self.request.user.userprofile.class.all()).order_by('id')
        qs2 = Books.objects.filter(class__in=self.request.user.userprofile.books.all()).distinct()
        context['qs1'] = qs1
        context['qs2'] = qs2
        return context

class ChartData(LoginRequiredMixin,APIView):
    model = Books
    authentication_classes = (SessionAuthentication, BasicAuthentication)
    permission_classes = (IsAuthenticated,)

    def get(self, request, format=None):
        qs_count = Books.objects.filter(class__in=self.request.user.userprofile.class.all()).count()
        labels = []
        default_items = []
        data = {
            "labels": labels,
            "default": default_items,
        }
        return Response(data)

这是我的Java语言HTML ...

Here's my HTML with the Javascript...

{% extends 'base5.html' %}

{% block body_block %}
<div class="box6">
          <h1 class="title">Number of Books By Class</h1>
<canvas id="myChart"></canvas>
<div>

<script>
var endpoint = '{% url "Books: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: 'bar',
            data: {
                labels: [{% for i in qs1 %}{{ i.id }},{% endfor %}],
                datasets: [{
                    label: "# of Books",
                     data: [{% for j in qs2 %}
                              {{ j.id }},
                            {% endfor %}],
                    backgroundColor: [
                        'rgba(255, 99, 132, 0.2)',
                        'rgba(255, 99, 132, 0.2)',
                        'rgba(54, 162, 235, 0.2)',
                        'rgba(255, 206, 86, 0.2)',
                        'rgba(75, 192, 192, 0.2)',
                        'rgba(153, 102, 255, 0.2)',
                        'rgba(255, 159, 64, 0.2)'
                    ],
                    borderColor: [
                        'rgba(255,99,132,1)',
                        'rgba(255,99,132,1)',
                        'rgba(54, 162, 235, 1)',
                        'rgba(255, 206, 86, 1)',
                        'rgba(75, 192, 192, 1)',
                        'rgba(153, 102, 255, 1)',
                        'rgba(255, 159, 64, 1)'
                    ],
                    borderWidth: 1
                }]
            }
        })
    },
    error: function(error_data){
        console.log("error")
        console.log(error_data)
    }
})
</script>

{% endblock %}

这里是模型.

class Books(models.Model):

    book_name = models.CharField(max_length=80,null=True)
    description = models.TextField(max_length=264,unique=False)
    class = models.ForeignKey(Class,on_delete=models.DO_NOTHING,related_name='classes')

class Class(models.Model):
    class_name = models.CharField(max_length=264,unique=True)
    teacher = models.ForeignKey(User,null=True,
                    on_delete=models.CASCADE,related_name="teacher_name")

我觉得问题所在是我在qs2中的循环逻辑.它没有正确遍历qs2,因为它正在返回结果,但不是正确的结果.我只是想从与班级相匹配的用户那里拿出书籍,但它不起作用.另外,我只能让"ID"显示在图表上,而不能获得实际的外键名称.我也不知道如何获得实际的外键名称来显示.感谢任何关于我做错事情的帮助或指示.我太近了!

I feel like my looping logic in qs2 is where the problem is. It is not properly looping through qs2, as it is returning results, but not the proper ones. I'm only trying to get the books out of the the user that match the class, and it's not working. Also, I can only get the "ID" to display on the graph, not the actual foreign key name. I can't figure out how to get the actual foreign key name to display either. Appreciate any help or pointers as to what I'm doing incorrectly. I'm so close!

推荐答案

尝试一下:

def get_context_data(self, **kwargs):
    context = super(ChartView, self).get_context_data(**kwargs)
    qs1 = Class.objects.filter(id__in=self.request.user.userprofile.class.all()).order_by('id')        
    class_names = [ cls.class_name for cls in qs1]
    books_count = [ Books.objects.filter(class=cls).count() for cls in qs1 ]
    context['qs1'] = class_names
    context['qs2'] = books_count
    return context

在这里,我希望按类对 Class Books 查询集进行排序,因为顺序至关重要.在这里,我直接在上下文中注入 Class 名称和 Books 计数.

Here i want both the Class and Books queryset to be ordered by class because the order is crucial. Here in the context i inject the Class names and Books count directly in the context.

模板中使用此规则:

<script>
        var labels = "{{ qs1 }}";
        var ctx = document.getElementById("myChart");
        var myChart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: Array.from(labels),
                datasets: [{
                    label: "# of Books",
                     data: [{% for j in qs2 %}
                              {{ j }},
                            {% endfor %}],
                    backgroundColor: [
                        'rgba(255, 99, 132, 0.2)',
                        'rgba(255, 99, 132, 0.2)',
                        'rgba(54, 162, 235, 0.2)',
                        'rgba(255, 206, 86, 0.2)',
                        'rgba(75, 192, 192, 0.2)',
                        'rgba(153, 102, 255, 0.2)',
                        'rgba(255, 159, 64, 0.2)'
                    ],
                    borderColor: [
                        'rgba(255,99,132,1)',
                        'rgba(255,99,132,1)',
                        'rgba(54, 162, 235, 1)',
                        'rgba(255, 206, 86, 1)',
                        'rgba(75, 192, 192, 1)',
                        'rgba(153, 102, 255, 1)',
                        'rgba(255, 159, 64, 1)'
                    ],
                    borderWidth: 1
                }]
            }
        })
    },
    error: function(error_data){
        console.log("error")
        console.log(error_data)
    }
})
</script>

不需要ajax请求,您已经从 context

There is no need for ajax request you already got the data from the context

我希望这会起作用.

这篇关于Django和Chart.js无法正确渲染图形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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