0

I'm trying to visualize my data to a graph using chart.js! However, I have no idea how that's done... Could you program experts help me with this, please?

Here's the code I had so far model.py

class MarksInputOne(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True)
date = models.DateTimeField(auto_now_add=True)
mark = models.CharField(max_length=200)

def __str__(self):
    return self.mark

views.py

def courseOne(request):
marks = MarksInputOne.objects.filter(user=request.user)
total_assign = TodoList.objects.filter(user=request.user)

total = total_assign.count()
this = total_assign.filter(category__name="MAT292H1").count()

return render(request, 'courses/firstcourse.html', {'marks': marks, 'total_assign': total_assign, 'total': total,
                                                    'this': this})


def lineChart(request):
labels =[]
data = []

queryset = MarksInputOne.objects.values('mark').filter(category__name='MAT292H1').order_by('date')
for entry in queryset:
    labels.append(entry['date'])
    data.append(entry['mark'])

return JsonResponse(data={
    'labels': labels,
    'data': data,
})

and finally, chart.html, this is actually an example code from chart.js

<div class="col">
    <div class="col-md">
        <h5>Graph</h5>
        <hr>
        <div class="card card-body">
            <canvas id="chart" width="800" height="400"></canvas>
            <script>
                var ctx = document.getElementById('chart').getContext('2d');
                var myChart = new Chart(ctx, {
                    type: 'line',
                    data: {
                        labels: [{{data}}],
                        datasets: [{
                            label: 'Academic Performance',
                            data: [{{ labels }}],
                            fill: false,
                            backgroundColor: [
                                '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: [
                                'rgb(255,99,132)',
                                '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
                        }]
                    },
                    options: {
                        scales: {
                            yAxes: [{
                                ticks: {
                                    beginAtZero: true
                                }
                            }]
                        }
                    }
                });
            </script>
        </div>
    </div>
</div>

Please help me to implement the data on the chart! I've been searching through internet for so long, couldn't find anything :((

Thank you for your help!!

1
  • The template tag json_script can be used to render an object as JSON so you can parse it in your JS Commented Aug 5, 2020 at 1:37

1 Answer 1

4

All that chart.js cares about is a list of labels, and a list of values. So you'll have to somehow provide it with that. Your lineChart view function responds with a list of labels and a list of datapoints so it suits our needs exactly. What you'll need to do is have your web page send a request to your django server to request the data it should display. When a response is received, you can feed in your data to chart.js and build your chart. Here's a stripped-down code of how all of this fits together from the client's side and from the server's side:

Server Side

def lineChart(request):    
    return JsonResponse(data = {
        'labels': ["Red Label", "Yellow Label"],
        'data': [5, 6],
    })

Client Side

<canvas id="chart"></canvas>
<script>
  let ctx = document.getElementById('chart');
  $.ajax({
    url: '/lineChart/',
    success: function(response){
      new Chart(ctx, {
        type: 'line',
        data: {
          labels: response.labels,
          datasets: [{
            data: response.data
          }]
        }
      });
    }
  });
</script>

One thing I should point out are the different languages we are dealing with here and how they interact. Django renders an HTML page. During this rendering process, it has access to python variables called context variables. After it's done rendering, it sends that final HTML page to the client. On the client's side is chart.js which is a JavaScript library, it needs JavaScript variables to work with. So using Django's context variables wouldn't really work. ...unless... you use django to render its context variables into the html page as hard-coded javascript-vaild values. I'm guilty of doing this in the past but I would not recommend this approach. It smells awful!

Sign up to request clarification or add additional context in comments.

7 Comments

I see! thank you very much for your comment. It makes so much more sense now. if you don't mind, could you show me the practical implementation specific to my code?? that'll be amazing
@Jayden.devpro did it not work when you tried it? I could edit my sample code to reflect yours but it'll mostly be irrelevant stuff, like chart.js options and stuff like that. The sample code I wrote should be enough to handle the functionality, unless I've missed something somewhere.
I tried your logic, but somehow it didn't work... If you don't mind, could you please reflect my case? that'll be sooo helpful
@Jayden.devpro As I was editing my post trying to make it more specific to your code, I realized that there was nothing of value that I was gonna add really. So my question to you is, why exactly did it not work? Did you include jquery? Did you trying logging the response to the console to check if it's in fact correct?
I think I have not added the ajax at all, which takes in Jsonresponse I think that's why the chart didn't take in any value
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.