Using Chart.js with Django

Chart.js Header

Chart.js is the new kid on on the block for JavaScript charts. Learn how to use them here to chart out the number of user registrations for the last 30 days.

The View

This view builds an array of people that registered on the site daily for the last 30 days.

from django.views.generic import TemplateView
from django.contrib.auth.models import User

import arrow


class AnalyticsIndexView(TemplateView):
    template_name = 'analytics/admin/index.html'

    def get_context_data(self, **kwargs):
        context = super(AnalyticsIndexView, self).get_context_data(**kwargs)
        context['30_day_registrations'] = self.thirty_day_registrations()
        return context

    def thirty_day_registrations(self):
        final_data = []

        date = arrow.now()
        for day in xrange(1, 30):
            date = date.replace(days=-1)
            count = User.objects.filter(
                date_joined__gte=date.floor('day').datetime,
                date_joined__lte=date.ceil('day').datetime).count()
            final_data.append(count)

        return final_data

The method thirty_day_registrations loops through from 1 to 30, and gets the count of registrations for that day. Then it returns that array back to the get_context_data method and assigns it to 30_day_registrations which is what we will use in our template.

The Template

The template is very basic in that it has just enough data to generate a line chart.

{% extends "base.html" %}

{% block extrahead %}
<script src="//cdnjs.cloudflare.com/ajax/libs/Chart.js/0.2.0/Chart.min.js" type="text/javascript"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$( document ).ready(function() {
    var data = {
        labels: ['1', '5', '10', '15', '20', '25', '30'],
        datasets: [
            {
                label: "Site Registrations in the Last 30 Days",
                fillColor: "rgba(220,220,220,0.2)",
                strokeColor: "rgba(220,220,220,1)",
                pointColor: "rgba(220,220,220,1)",
                pointStrokeColor: "#fff",
                pointHighlightFill: "#fff",
                pointHighlightStroke: "rgba(220,220,220,1)",
                data: {{ 30_day_registrations }}
            }
        ]
    };
    var ctx = document.getElementById("myChart").getContext("2d");
    var myLineChart = new Chart(ctx).Line(data);
});
</script>
{% endblock %}

{% block content %}
<canvas id="myChart" width="500" height="300"></canvas>
{% endblock %}

If we go line-by-line of the important parts this should make more sense.

<canvas id="myChart" width="500" height="300"></canvas>

This is where in the page your chart is going to show up its only real requirement is it has an id and is a canvas object.

var ctx = document.getElementById("myChart").getContext("2d");

This gets us the canvas element for us to feed data to so we can see our chart.

var myLineChart = new Chart(ctx).Line(data);

We create a Chart object and pass it our canvas element. Then we create our Line chart using a data object we are going to create.

var data = {
    labels: ['1', '5', '10', '15', '20', '25', '30'],
    datasets: [
        {
            label: "Site Registrations in the Last 30 Days",
            fillColor: "rgba(220,220,220,0.2)",
            strokeColor: "rgba(220,220,220,1)",
            pointColor: "rgba(220,220,220,1)",
            pointStrokeColor: "#fff",
            pointHighlightFill: "#fff",
            pointHighlightStroke: "rgba(220,220,220,1)",
            data: {{ 30_day_registrations }}
        }
    ]
};

This is an example data object to create a chart. Most of it is self-explanatory, but the keys parts are:

  • labels: this is outside of the datasets object.
  • datasets: you can have multiple json objects in here for more lines in chart
  • data: in this case it is just an array, which in this case we are generating in our view and outputting here.

Conclusion

Chart.js is a great library for doing charting, especially if your primary audience is using more modern browsers. I have been looking at charting libraries, but so far this has been one of the best ones of both paid and free ones. The best part is right now chart.js is free. So if you need to do some charting I would say give it a shot.

comments powered by Disqus