Server-rendered charts in Django

Ray Chen
HackerNoon.com
2 min readSep 3, 2017

--

Say, you’re building a Django-powered web application and you have some data you want to visualize. How do you do it? The most popular option is to pick a front-end charting library, have the back-end send the dataset (either through an API or directly passing it to the template) to the front-end, and render the chart in the browser. This approach allows the front-end to do most of the heavy lifting, thereby reducing the strain on your server.

But… What if you don’t want to deal with Javascript? What if the library you pick requires a license for commercial use (e.g. Highcharts, Amcharts, etc.)? What if you just need something quick?

Enter the alternative approach: render the chart on the back-end and insert the rendered HTML/SVG in the template. No Javascript, everything in Python, no front-end maintenance for your charts required. I’ll be showing you how to do this with Pygal.

Pygal supports many different types of charts (even maps!), along with a powerful configuration system and built-in styles (no need to fiddle with JS/CSS here). It also lets you output the chart in many different ways.

First, let’s install Pygal:

$ pip install pygal

I will be skipping Django project set-up and assuming you either have an existing project to work with, or you know how to get one running. We will need some data to work with, so I’ll create a model with mock data:

Now, here’s the fun part — there’s really only three steps required to get everything working:

1. Create a Pygal chart

I like to keep my charts and views separate — chart generation and any data queries should not be in the view. Create a new file in your app’s directory (same as your models.py, views.py, etc.) named charts.py and put all chart-related logic in here, like so:

2. Generate the chart’s SVG pass it to template context

3. Include it in template

The chart’s SVG is now available through {{ cht_fruits|safe }}. The safe filter is required here; Django would escape the SVG otherwise. If you want tooltips to work, you’ll have to include the Pygal tooltips JS file:

<script type="text/javascript" src="http://kozea.github.com/pygal.js/latest/pygal-tooltips.min.js"></script>

And here’s the rendered chart:

Rendered Chart

--

--