Chartjs-Make a pie chart using chart.js in Django error

0👍

You are trying to pass the entire queryset to the chart data, but you need to group the transactions by category and sum the amounts for each category to display the proportion of expenses under each category.

Update your ExpenseStructureView class with the code below:

class ExpenseStructureView(TemplateView):
template_name = 'expense_structure.html'

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    qs = Transaction.objects.values('category').annotate(total_amount=Sum('amount')).order_by('category')
    context["categories"] = [d['category'] for d in qs]
    context["totals"] = [d['total_amount'] for d in qs]
    return context

The code has been updated to group the transactions by category and sum the amounts for each category, then pass the resulting data to the chart in the template.

After this you need to update your expense_structure.html template file with this:

{% extends 'base_content.html' %}
{% block content %}
<h1>Expense Structure!</h1>
<script>
    // jquery function
    $(document).ready(function(){
        var ctx = document.getElementById('myChart').getContext('2d');
        var myChart = new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: {{ categories|safe }},
                datasets: [{
                    label: 'Expense',
                    data: {{ totals|safe }},
                    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: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
});
    });
</script>

<canvas id="myChart" width="400" 
height="100"></canvas>
{% endblock %}

Leave a comment