0

I'm trying to plot a graph from the database by using axios endpoint to get the data. I suspect it has something to do with the format. As I can see still see the correct data when navigating to api/chart/data/.

I have two variables, one is working fine but another is undefined: total_km and sorted_vehicle_list

so when I console.log(labels), it said "Error Cannot read property 'hidden' of undefined"

P.S. sorted_vehicle_list has one only instance and returns as a list [] (which I'm sure if it's the problem)

I have tried to print the output of the query in views.py and the output is correct. It returns the data that I want but somehow Chart.js can't see it.


class ChartData(APIView):
    authentication_classes = []
    permission_classes = []

    def get(self, request, format=None):
        all_vehicles = LoggerRecord.objects.values('imei').distinct()
        vehicle_list = []

        for vehicle in all_vehicles:
            vehicle_list.append(vehicle['imei'])

        sorted_vehicle_list = sorted(vehicle_list)

        #create sum km
        total_km = LoggerRecord.objects.aggregate(Sum('distance'))

        print(total_km)
        print(all_vehicles)

        data = {
            'all_vehicles': all_vehicles,
            'total_km': total_km
        }

        return Response(data)

axios.get(endpoint)
  .then(function (response) {
    labels = response.data.sorted_vehicle_list
    total_km = response.data.total_km
    console.log(labels)
    console.log(total_km)
    var ctx = document.getElementById('myChart').getContext('2d');

    var chart = new Chart(ctx2, {
        // The type of chart we want to create
        type: 'bar',
        // The data for our dataset
        data: {
            labels: labels,
            datasets: [{
                label: 'Total KM',
                backgroundColor: 'rgb(255, 99, 132)',
                borderColor: 'rgb(255, 99, 132)',
                data: total_km 
            }]
        }
        //console.log(response);
    })
Alexis
  • 1
  • 1
  • I don't think the issue is with django. you debug in the Javascript and check the data type by using **typeof** func in javascript – Sakthi Panneerselvam May 02 '19 at 07:44
  • @SakthiPanneerselvam it turns out that both are object. Hmm I'm not sure if it's Chart.js takes in object or just a list. – Alexis May 03 '19 at 00:06
  • https://stackoverflow.com/questions/757022/how-do-you-serialize-a-model-instance-in-django convert you django model object to json and debug from django side – Sakthi Panneerselvam May 03 '19 at 05:16

0 Answers0