对象列表到图表标签不起作用

时间:2018-03-10 16:54:37

标签: javascript django chart.js

我有下一个视图,我得到三个列表。

1日期列表

用户在一个时间范围内提出的2个问题。

同一时间范围内用户的3个答案。

views.py

data_list_question = []
data_list_answer = []
timeline = []
for n in range(24,0,-4):
    t1 = timedelta(weeks=n)
    t2 = timedelta(weeks=n-4)
    c = today-t1
    timeline.append(c)
    a = int(question.objects.filter(published_date__gt=(today-t1), published_date__lt=(today-t2)).count())
    data_list_question.append(a)
    b = answer.objects.filter(published_date__gt=(today-t1), published_date__lt=(today-t2)).count()
    data_list_answer.append(b)

然后我在模板中的scipt中使用这个值,如下一个:

chart.html

<script type="text/javascript">
    $( document ).ready(function() {
        var ctx = document.getElementById("lineChartstats");
        var lineChart = new Chart(ctx, {
                type: 'line',
                data: {
                        labels: {{ timeline|date:"j b" }},
                        datasets: [{
                                label: "Questions",
                                backgroundColor: "rgba(38, 185, 154, 0.31)",
                                borderColor: "rgba(38, 185, 154, 0.7)",
                                pointBorderColor: "rgba(38, 185, 154, 0.7)",
                                pointBackgroundColor: "rgba(38, 185, 154, 0.7)",
                                pointHoverBackgroundColor: "#fff",
                                pointHoverBorderColor: "rgba(220,220,220,1)",
                                pointBorderWidth: 1,
                                data: {{ data_list_question}}
                        }, {
                                label: "Answers",
                                backgroundColor: "rgba(3, 88, 106, 0.3)",
                                borderColor: "rgba(3, 88, 106, 0.70)",
                                pointBorderColor: "rgba(3, 88, 106, 0.70)",
                                pointBackgroundColor: "rgba(3, 88, 106, 0.70)",
                                pointHoverBackgroundColor: "#fff",
                                pointHoverBorderColor: "rgba(151,187,205,1)",
                                pointBorderWidth: 1,
                                data: {{ data_list_answer }}
                        }]
                },
        });
});
</script>

问题是每个数据集的数据都有效,但标签的“时间轴”不起作用。我不知道如何解决这个问题。

提前致谢!

2 个答案:

答案 0 :(得分:0)

我认为:[{% for t in timeline %}t|date:"j b",{% endfor %}]

答案 1 :(得分:0)

解决方案

首先在视图中使用json对数据进行编码:

json_timeline = json.dumps(timeline)

在模板脚本中:

labels: {{timeline|safe}},

我从附件链接获取信息:Pass a list of string from Django to Javascript