0

I am building a web application that will allow users to compare the amount of calories they have burned during exercise vs the amount they have consumed in a meal. To do this I am using ChartJS. Just to start i am hard coding in data to get an idea of how the graph works/looks on the page.

The problem is that when I run the app the chart page is blank. Below is how I have tried to implement the chart:

Views

This is where I am creating the Chart view. The data is hard coded in for the time being.

class ChartView(View):
    def get(self, request, *args, **kwargs):
        return render(request, 'nutrition/chart.html', {"users": 10})

def get_data(request, *args, **kwargs):
    data = {
        "calories_in": 200,
        "calories_out": 300
    }
    return JsonResponse(data)


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

    def get(self, request, format=None):
        qs_count = User.objects.all().count()
        labels = ["Users", "Blue", "Yellow", "Green", "Purple", "Orange"]
        default_items = [qs_count, 12, 22, 13, 11, 15]
        data = {
                "labels": labels,
                "default": default_items,
        }
        return Response(data)

HTML

Here is my html page that I am using to display the chart. I have added all the relevant imports that are need for chartjs javascript.

<script>

        {% block jquery %}
            var endpoint = 'nutrition/api/chart/data/'
            var defaultData = []
            var labels = [];
            $.ajax({
                method: "GET",
                url: endpoint,
                success: function(data) {
                    labels = data.labels
                    defaultData = data.default
                    setChart()
                },
                error: function (error_data) {
                    console.log("error")
                    console.log(error_data)

                }
            })

            function setChart() {
                var ctx = document.getElementById("myChart");
                var myChart = new Chart(ctx, {
                    type: 'bar',
                    data: {
                        labels: labels,
                        datasets: [{
                            label: '# of Votes',
                            data: defaultData,
                            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: [
                                '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
                        }]
                    },
                    options: {
                        scales: {
                            yAxes: [{
                                ticks: {
                                    beginAtZero:true
                                }
                            }]
                        }
                    }
                });
            }

    {#        var ctx = document.getElementById("myChart");#}


        {% endblock %}
    </script>

    {% block body %}

        <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
        <script type="text/javascript"></script>

        <div class="row">
            <div class="container">
                <div class="col-sm-12" url-endpoint="'{% url "nutrition:chart" %}">
                    <h1>Chart</h1>
                    <canvas id="myChart" width="400" height="400"></canvas>

                </div>
            </div>
        </div>
    {% endblock body %}

Urls

All of my urls are an extension of nutrition/

urlpatterns = [
    # url for the webpage to display the chart
    url('^chart/$', ChartView.as_view(), name='chart'),
    # url to show the data using the django rest_framework
    url('^api/chart/data/$', ChartData.as_view()),
]

Edit This is the what i see when I check under the network tab at the nutrition/api/chart/data url.

enter image description here

4
  • Are there any errors in the browser console? Commented Apr 23, 2018 at 13:52
  • No there is no errors in the browser console Commented Apr 23, 2018 at 14:05
  • Looking at the code your chart is called when you get a successful response from the server. In chrome/firefox under the network tab can you see a JSON dictionary response from nutrition/api/chart/data/? Commented Apr 23, 2018 at 15:28
  • I've attached a screen grab of what is displayed in the network tab at the nutrition/api/chart/data url Commented Apr 23, 2018 at 16:10

2 Answers 2

1

Your Django service is set to return an HTML response instead of a JSON payload. Add the following settings to your settings.py file and theoretically your application should be up and running.

REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework.renderers.JSONRenderer',
    ),
}
`
Sign up to request clarification or add additional context in comments.

Comments

0

I followed a similar tutorial on YouTube. I am a total newbie and came across this question, when I am trying to figure out how this thing works.
From what I understand <div class="col-sm-12" url-endpoint="'{% url "nutrition:chart" %}"> I think something is wrong with the Url endpoint, why is it pointing at ChartView() when you are inside ChartData().
Also, your url patterns don't quiet align with your charts.html end point. Again, I am a total newbie, I am only talking about different patterns from what I saw in the tutorial. I am referring to
"CodingEntrepreneurs -channel : Django + Chart.js // Learn to intergrate Chart.js with Django -video"

Comments

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.