article

Tuesday, June 23, 2020

How to Use Chart-js with Django Example Pie Chart


How to Use Chart-js with Django Example Pie Chart

Chart.js is a open source JavaScript library that helps you render HTML5 charts.

In this tutorial we are going to Pie Chart based on data extracted from our models.

You can download it from Chart.js official website and use it locally, or you can use it from a CDN using the URL above.


https://www.chartjs.org/ myapp/models.py
#models.py
from django.db import models
 
class City(models.Model):
    name = models.CharField(max_length=30)
    population = models.PositiveIntegerField()
 
    def __str__(self):
        return self.name
   
    class Meta:
        db_table = 'myapp_city'
python manage.py makemigrations myapp
python manage.py migrate

New database table added

CREATE TABLE myapp_city (
id INTEGER NOT NULL
PRIMARY KEY AUTOINCREMENT,
name VARCHAR (30) NOT NULL,
population INTEGER

); devproject/urls.py
#urls.py
from django.contrib import admin  
from myapp import views  
from django.conf.urls import url
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.home, name='home'),
    path('pie-chart/', views.pie_chart, name='pie-chart'),
]
myapp/views.py
#views.py
from django.shortcuts import render, redirect

from myapp.models import City

def home(request):
    return render(request, 'home.html')

def pie_chart(request):
    labels = []
    data = []

    queryset = City.objects.order_by('-population')[:9]
    for city in queryset:
        labels.append(city.name)
        data.append(city.population)

    return render(request, 'pie_chart.html', {
        'labels': labels,
        'data': data,
    })
myapp/templates/home.html
//templates/home.html
{% extends 'base.html' %}
{% block title %}Home {% endblock %}


{% block content %}
<h1>Pie Chart Population</h1>
 <div id="container" style="width: 75%;">
    <canvas id="pie-chart"></canvas>
 </div>
  <script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js"></script><script>
    var config = {
      type: 'pie',
      data: {
        datasets: [{
          data: [1780000, 1630000, 582602, 416522, 411634, 318332, 318332, 306659, 233040],
          backgroundColor: [
            '#ff0000', '#0000ff', '#ff0080', '#73ffff', '#5c26ff', '#002db3', '#ffff26', '#4cff4c', '#ff00ff'
          ],
          label: 'Population'
        }],
        labels: ['Manila City', 'Davao City', 'Makati', 'Pasay City', 'Angeles City', 'Tarlac City', 'Malolos', 'San Fernando', 'Olongapo City']
      },
      options: {
        responsive: true
      }
    };

    window.onload = function() {
      var ctx = document.getElementById('pie-chart').getContext('2d');
      window.myPie = new Chart(ctx, config);
    };
  </script>
{% endblock %}
myapp/templates/pie_chart.html
//templates/pie_chart.html
{% extends 'base.html' %}

{% block title %}Django Highcharts - Pie Chart{% endblock %}

{% block content %}
<h1>Pie Chart Population</h1>
 <div id="container" style="width: 75%;">
    <canvas id="pie-chart"></canvas>
  </div>
  <script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js"></script><script>
    var config = {
      type: 'pie',
      data: {
        datasets: [{
          data: {{ data|safe }},
          backgroundColor: [
            '#ff0000', '#0000ff', '#ff0080', '#73ffff', '#5c26ff', '#002db3', '#ffff26', '#4cff4c', '#ff00ff'
          ],
          label: 'Population'
        }],
        labels: {{ labels|safe }}
      },
      options: {
        responsive: true
      }
    };

    window.onload = function() {
      var ctx = document.getElementById('pie-chart').getContext('2d');
      window.myPie = new Chart(ctx, config);
    };
  </script>
{% endblock %}
myapp/templates/base.html
//templates/base.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
 <title>{% block title %}Django Highcharts {% endblock %}</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <a class="navbar-brand" href="#">Cairocoders</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
    <div class="navbar-nav">
   <a class="nav-item nav-link active" href="">Home</a>
    </div>
  </div>
</nav>
 <div class="container" style="padding:20px;">
    <div class="col-md-12 well">
        <h3 class="text-primary">How to Use Chart-js with Django Example Pie Chart</h3> 
        <hr style="border-top:1px dotted #ccc;"/>
  {% block content %} {% endblock %}
    </div>
    </div> 
</body>
</html>

Related Post