In this article, we will create a bar chart to visualize the department table of student count.
We will show you how to integrate Django, a high-level Python Web framework,
Sqlite(DataBase) with Angular Framework to populate the data using the official Highcharts Angular wrapper.
Let’s get started.
There are three main parts to create this project. The first part is to set up a Python environment with Python Web framework and Sqlite(DataBase). The second part is to make the app. The third part is to create an Angular project with Highcharts by using the official Highcharts Angular wrapper.
Set up a Python environment
There are 6 steps in the first part:
1. Install python.
2. Create the local environment for project D:\Django-Angular-Highcharts>python -m venv myenv
The result is the myenv folder
3. Activate the local python environment. Before installing or using packages in the virtual environment, activating the local python environment is necessary. Activating a virtual setting will put the virtual environment-specific python and pip executables into your shell’s PATH D:\Django-Angular-Highcharts>myenv\Scripts\activate
4. Install django with command (myenv) D:\Django-Angular-Highcharts>pip install django
5. Install the django rest framework. (myenv) D:\Django-Angular-Highcharts>pip install djangorestframework
6. Create the project(DjangoProject) (myenv) D:\Django-Angular-Highcharts>django-admin startproject DjangoAPI
Here is a picture of the folder structure created by django-admin:
You can find below a short description of each folder:
- manage.py: A command-line utility that lets you interact with this Django project in various ways. It allows us to create applications, work with databases, and start the development web server.
- __init__.py: An empty file that tells Python that this directory should be considered a Python package.
- settings.py: Settings/configuration for this Django project. Django settings will tell you all about how settings work. We can use settings.py for registering any created applications, the static files’ location, database configuration details, etc.
- Urls.py: This could contain your application urls mapping , defining url mapping of your application.
- asgi.py: An entry-point for ASGI-compatible web servers to serve your project.
- wsgi.py: An entry-point for WSGI-compatible web servers to serve your project(Is used to help Django application communicates with the webserver)
7. Now, it is time to check if the project was created successfully. To do that just run (myenv) D:\Django-Angular-HighCharts\DjangoAPI>python manage.py runserver
.
Then, check the result using this link http://127.0.0.1:8000/ on a browser. Here is the result in the folder db.sqlite3 following the execution of the previous command:
8. The last step in this section is to set up a database. Just download the sqlite https://sqlitestudio.pl/, then Open SQLiteStudio and add the db.sqlite database
Remark
sqlite database is the default database, which comes by default in settings.py; however, feel free to use any other databases
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } }
Let’s create the application
1. First, let’s install CORS by running the pip install django-cors-headers
command to allow the communication between Angular and Django, django-cors-headers and django rest framework need to be registered in settings.py, which is inside DjangoApi project.
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'rest_framework' ]
Don’t forget to add corsheaders.middleware.CorsMiddleware
in the middleware array and CORS_ORIGIN_ALLOW_ALL=True
in the same file i.e setting.py
CORS_ORIGIN_ALLOW_ALL=True
MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ]
2. Let’s create our app inside DjangoAPI project (myenv) D:\Django-Angular\DjangoAPI>python manage.py
startapp Department
Then register the Department.apps.DepartmentConfig
, into the DjangoApi project’s setting.py file
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Department.apps.DepartmentConfig', 'corsheaders', 'rest_framework' ]
3. Now, let’s create a model for the application in models.py file of the application
from django.db import models class Departments(models.Model): DepartmentId=models.AutoField(primary_key=True) DepartmentName=models.CharField(max_length=100) StudentCount=models.CharField(max_length=100)
4. Create the migrations for your app(Department) (myenv) D:\Django-Angular\DjangoAPI>python manage.py makemigrations Department
The result is an initial.py file inside the migrations folder to track will go into the database.
The same command will generate a database with the name ”db” with no tables.
5. Commit those changes to the database (myenv) D:\Django-Angular\DjangoAPI>python manage.py migrate Department
You will see two tables, one for the migrations and the one for our app.
6. Create serializers.py to serialize the python data model to any data type. We imported serializers from rest_framework and Departments from Department.model
from rest_framework import serializers from Department.models import Departments class DepartmentSerializer(serializers.ModelSerializer): class Meta: model=Departments fields=('DepartmentId','DepartmentName','StudentCount')
7. Create the views for the application in views.py. The data is serialized and converted into JSON format.
from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from rest_framework.parsers import JSONParser from django.http.response import JsonResponse from Department.models import Departments from Department.serializers import DepartmentSerializer # Create your views here. @csrf_exempt def departmentApi(request,id=0): if request.method=='GET': departments=Departments.objects.all() department_serializer=DepartmentSerializer(departments,many=True) return JsonResponse(department_serializer.data,safe=False)
8. Let’s create the urls.py file; this file is in charge of mapping the project’s routes and paths. In this case, the purpose of the utls.py is to fetch the data department
from django.conf.urls import url from Department import views from django.conf.urls.static import static from django.conf import settings urlpatterns=[ url(r'^department/$',views.departmentApi) ]
9. To configure any URL, it is necessary to register the url.py of app(Department) into the main project(DjangoAPI). Keep in mind that DjangoAPI is a project, and Department is the application.
url(r'^',include('Department.urls')) from django.contrib import admin from django.urls import path from django.conf.urls import url,include urlpatterns = [ path('admin/', admin.site.urls), url(r'^',include('Department.urls')) ]
Set up an Angular project with Highcharts
1. To set up an Angular project, follow angular instructions Setting up the local environment and workspace. To visualize the data, include the official Highcharts Angular wrapper Highcharts Angular wrapper, then import the Highcharts module:
- To install highcharts-angular and the Highcharts library, just run the following instruction:
npm install highcharts-angular --save
- To import the package go to app.module.ts file and import the module HighchartsChartModule from the highcharts-angular package.
- To build Highcharts charts, install Highcharts:
npm install highcharts --save
Next, in the app.component.ts, in top lines where other imports are, add another one for Highcharts:import * as Highcharts from 'highcharts';
Remark
The Django development server is running on http://127.0.0.1:8000 (check the code on Github)
2. The last step is to initialize the chart data and options by adding the highcharts-chart directive and some property binding into app.component.html:
<highcharts-chart *ngIf="chartOptions" [Highcharts]="Highcharts" [options]="chartOptions" style="width: 100%; height: 400px; display: block;"> </highcharts-chart>
And here is the final result:
As you can see on the GIF below, the bar chart gets the data from the database
Well, that is it. Now, you know how to combine Django, a high-level Python Web framework,
Sqlite(DataBase) with Angular Framework, and the official Highcharts Angular.
Comments
Ben | 3 years ago
This is really useful, thanks for it!
Want to leave a comment?
Comments are moderated. They will publish only if they add to the discussion in a constructive way. Please be polite.