Creating a Beautiful Dashboard with Django and Chart.js

So, I’ve been working on a website to accompany an AP Calculus Practice book that I’ve been writing for some time. When it’s finished, it’ll be eekatta.com and our perfect eekatta practice book. Right now we own the domain but we don’t own anything else.

Right now there’s not a lot of info out there on how to do this and mainly it’s because it’s SO DAMN EASY. My web framework of choice is Django. I love Python and I love simple programming abstractions and Django is SUPER fast and really clean.

Similarly, Chart.js is a great open source library that allows beautiful and flexible front end configuration for vending data. It had great documentation and comes with a wealth of examples.

Preliminary Notes

You might google search and find a library called django-chart.js . I actually started with this, as it seemed to me like a great, fast method to get setup. Unfortunately, I found 2 things I didn’t like:

  1. The paradigm is to setup a django page view to serve the json and then parse it through a call in the html. While this is clean and keeps the data off the page itself, I HATE spinning up and serving all those other pages. It always seems weird to me.
  2. There’s very little documentation. So if you only want to do the 4-5 things that are given in the examples, you’re golden. But as soon as you want to start serving multiple datasets and doing radar charts, things get tricky fast. Django and chart.js are so easy to setup together that pouring through the library code actually becomes more inconvenient than doing it yourself.

Let’s Do It

This tutorial already assumes that you are already setup with a django instance running on your [local] host.

The rough outline is as follows, and corresponding code is given below for each of these tasks:

  1. Add the url for your beautiful charts to your urls.py file.
  2. Add the view to serve this information to views.py. In the example below I’m really generating nonsense numbers just to show, but I think this illustrates the point.
  3. Create a template in your templates folder that has the chart.js javascript and relevant elements and uses the data supplied by views.py. Ensure that the lists are not auto-escaped

Code

Below is all the code you should need to get you started. I focus on only the specific aspects of code you’ll need to ADD to your project to get this thing all up and working. You don’t need models or anything else to do this, in fact, if you have the skeleton of your django project setup the below could be the very first application page that you render!

An example is worth a million words!

urls.py

from django.urls import path

from . import views

urlpatterns = [
    # ... other urls here ... #
    path('dashboard/', views.user_dashboard, name='user_dashboard'), # this is the URL we're going to create
]

views.py

import random
import names       # For generating random names and labels - pip install names

# ... other views information ... #

def user_dashboard(request):
    n = 10 # number of samples to generate
    labels = [names.get_full_name() for i in range(n)]
    data = [round(random.random(),2) for i in range(n)]
    context = {"labels": labels,
               "data": data}
    return render(request, 'dashboard.html', context)

dashboard.html

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
<script type="text/javascript" src="{% static 'js/Chart.min.js' %}"></script>
</head>
<body>

<!-- create the div and canvas to drop the chart.js element into just javascript on page render -->
<div class="contained">
      <canvas id="myChart2"></canvas>
</div>

<!-- javascript to render the data from django into the chart.js object. Note the autoescape is off and the location of the {{labels}} and {{data}} elements -->
{% autoescape off %}
	<script type="text/javascript">
	new Chart(document.getElementById("myChart2"),
				{"type":"radar",
							"data":{"labels": {{labels}} ,
					 "datasets": [
								 {"label":"Percent Correct","data":{{data}},"fill":true,"backgroundColor":"rgba(54, 162, 235, 0.2)","borderColor":"rgb(54, 162, 235)","pointBackgroundColor":"rgb(54, 162, 235)","pointBorderColor":"#fff","pointHoverBackgroundColor":"#fff","pointHoverBorderColor":"rgb(54, 162, 235)"}
						    ]
					},
		
				 "options": {
					 "elements": {
						"line":{"tension":0,"borderWidth":3} 
						},
					"scale": {
						"ticks": {"max": 100, "min": 0, "stepSize": 20}
    						}
	     				}
										
				}
		);
	</script>
{% endautoescape %}


</body>
</html>

Final Thoughts

With this template and a little knowledge of javascript, you can easily extend this to multiple data elements and all the different chart types that chart.js has to offer.

Models give you the ability to configure rendered data for anything your app has to offer.

Happy (beautiful!) coding!

Leave a Reply

Your email address will not be published. Required fields are marked *