Plotting Charts

Learn to add static charts to your Django admin page.

We'll cover the following

Plotting charts

Now that you know how to extend the Django admin templates, you can imagine what you want as new features.

As an example, you will learn how to integrate the chart.js library in your Author list page view.

In your sample_app/templates/admin/sample_app/author/change_list.html you will find the {{block.super}} and load the chart.js library (line 7 in unedited file).

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.css"/>
<script src= "https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js"> </script>

Instead of having to fetch them from the internet, the static files have been placed in the project (in the sample_app/static/admin/assets folder), and these static files will be used. For this, you will include the following code snippet:

<link rel="stylesheet" type="text/css" href="{% static 'admin/assets/Chart.min.css' %}" />
<script src="{% static 'admin/assets/Chart.bundle.min.js' %}"></script>

Now you will add the javascript code to load chart.js sample code.

But before that, you need to inject the javascript code once your document content has loaded. For the insertion of the code, you will write the following at the end of your sample_app/templates/admin/sample_app/author/change_list.html file (line 94 of unedited file):

<script>
document.addEventListener('DOMContentLoaded', () => {

const ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
    labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        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
            }
        }]
    }
}
});

});
</script>

In your block {% block content %}, you will create your canvas (line 45 of unedited file):

<canvas id="myChart" width="400" height="50"></canvas>

Now, if you refresh your Author list page:

Get hands-on with 1400+ tech skills courses.