0

I have the next view, where I get three lists.

1-dates list

2-questions made by users in a time range.

3-answers of users in the same time range.

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)

Then I use this values in a scipt in the template like next:

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>

The problem is that the data for each dataset works, however the labels 'timeline' does not work. I do not know how to solve this problem.

Thanks in advance!

JohnWire
  • 97
  • 2
  • 12

2 Answers2

0

I think something like: [{% for t in timeline %}t|date:"j b",{% endfor %}]

HenryM
  • 5,557
  • 7
  • 49
  • 105
0

Solution

First encoding the data with json in the view:

json_timeline = json.dumps(timeline)

And the in the template script:

labels: {{timeline|safe}},

I get the information from the attached link: Pass a list of string from Django to Javascript

JohnWire
  • 97
  • 2
  • 12