How to create an analytics dashboard in a Django app (2023)

/ #Python
How to create an analytics dashboard in a Django app (1)
Veronika Rovnik
How to create an analytics dashboard in a Django app (2)

Hi folks!

Python, data visualization, and programming are the topics I'm profoundly devoted to. That’s why I’d like to share with you my ideas as well as my enthusiasm for discovering new ways to present data in a meaningful way.

The case I'm going to cover is quite common: you have data on the back end of your app and want to give it shape on the front end. If such a situation sounds familiar to you, then this tutorial may come in handy.

After you complete it, you’ll have a Django-powered app with interactive pivot tables & charts.

Prerequisites

To confidently walk through the steps, you need a basic knowledge of the Django framework and a bit of creativity. ✨

To follow along, you can download the GitHub sample.

Here's a brief list of tools we’re going to use:

If you have already set up a Django project and feel confident about the basic flow of creating apps, you can jump straight to the Connecting data to Flexmonster section that explains how to add data visualization components to it.

Let's start!

Getting started with Django


First things first, let’s make sure you’ve installed Django on your machine. The rule of thumb is to install it in your previously set up virtual environment - a powerful tool to isolate your projects from one another.

Also, make sure you’ve activated in a newly-created directory. Open your console and bootstrap a Django project with this command:

django-admin startproject analytics_project

Now there’s a new directory called analytics_project. Let’s check if we did everything right. Go to analytics_project and start the server with a console command:

python manage.py runserver

Open http://127.0.0.1:8000/ in your browser. If you see this awesome rocket, then everything is fine:

How to create an analytics dashboard in a Django app (3)

Next, create a new app in your project. Let’s name it dashboard:

python manage.py startapp dashboard

Here's a tip: if you're not sure about the difference between the concepts of apps and projects in Django, take some time to learn about it to have a clear picture of how Django projects are organized.

Here we go. Now we see a new directory within the project. It contains the following files:

__init__.py to make Python treat it as a package

admin.py - settings for the Django admin pages

apps.py - settings for app’s configs

(Video) Charts and Data Visualization | Django Inventory Management System Web Application

models.py - classes that will be converted to database tables by the Django’s ORM

tests.py - test classes

views.py - functions & classes that define how the data is displayed in the templates

Afterward, it’s necessary to register the app in the project.
Go to analytics_project/settings.py and append the app's name to the INSTALLED_APPS list:

INSTALLED_APPS = ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dashboard',]

Now our project is aware of the app’s existence.

Views


In the dashboard/views.py, we’ll create a function that directs a user to the specific templates defined in the dashboard/templates folder. Views can contain classes as well.

Here’s how we define it:

from django.http import JsonResponsefrom django.shortcuts import renderfrom dashboard.models import Orderfrom django.core import serializersdef dashboard_with_pivot(request): return render(request, 'dashboard_with_pivot.html', {})

Once called, this function will render dashboard_with_pivot.html - a template we'll define soon. It will contain the pivot table and pivot charts components.

A few more words about this function. Its request argument, an instance of HttpRequestObject, contains information about the request, e.g., the used HTTP method (GET or POST). The method render searches for HTML templates in a templates directory located inside the app’s directory.

We also need to create an auxiliary method that sends the response with data to the pivot table on the app's front-end. Let's call it pivot_data:

def pivot_data(request): dataset = Order.objects.all() data = serializers.serialize('json', dataset) return JsonResponse(data, safe=False)

Likely, your IDE is telling you that it can’t find a reference Order in models.py. No problem - we’ll deal with it later.

Templates

For now, we’ll take advantage of the Django template system.

Let's create a new directory templates inside dashboard and create the first HTML template called dashboard_with_pivot.html. It will be displayed to the user upon request. Here we also add the scripts and containers for data visualization components:

<head> <meta charset="UTF-8"> <title>Dashboard with Flexmonster</title> <script src="https://cdn.flexmonster.com/flexmonster.js"></script> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <link rel="stylesheet" href="https://cdn.flexmonster.com/demo.css"></head><body><div id="pivot-table-container" data-url="{% url 'pivot_data' %}"></div><div id="pivot-chart-container"></div></body>

Mapping views functions to URLs

To call the views and display rendered HTML templates to the user, we need to map the views to the corresponding URLs.

Here's a tip: one of Django's URL design principles says about loose coupling, we shouldn't make URLs with the same names as Python functions.

Go to analytics_app/urls.py and add relevant configurations for the dashboard app at the project's level.

from django.contrib import adminfrom django.urls import path, includeurlpatterns = [ path('admin/', admin.site.urls), path('dashboard/', include('dashboard.urls')),]

Now the URLs from the dashboard app can be accessed but only if they are prefixed by dashboard.

After, go to dashboard/urls.py (create this file if it doesn’t exist) and add a list of URL patterns that are mapped to the view functions:

from django.urls import pathfrom . import viewsurlpatterns = [ path('', views.dashboard_with_pivot, name='dashboard_with_pivot'), path('data', views.pivot_data, name='pivot_data'),]

Model


And, at last, we've gotten to data modeling. This is my favorite part.

As you might know, a data model is a conceptual representation of the data stored in a database.

Since the purpose of this tutorial is to show how to build interactive data visualization inside the app, we won’t be worrying much about the database choice. We’ll be using SQLite - a lightweight database that ships with the Django web development server.

But keep in mind that this database is not the appropriate choice for production development. With the Django ORM, you can use other databases that use the SQL language, such as PostgreSQL or MySQL.

For the sake of simplicity, our model will consist of one class. You can create more classes and define relationships between them, complex or simple ones.

Imagine we're designing a dashboard for the sales department. So, let's create an Order class and define its attributes in dashboard/models.py:

from django.db import modelsclass Order(models.Model): product_category = models.CharField(max_length=20) payment_method = models.CharField(max_length=50) shipping_cost = models.CharField(max_length=50) unit_price = models.DecimalField(max_digits=5, decimal_places=2)

Working with a database


Now we need to create a database and populate it with records.

(Video) How to Create Django Custom Dashboard || Django Tutorial || Django Admin Panel || Frontend Source

But how can we translate our model class into a database table?

This is where the concept of migration comes in handy. Migration is simply a file that describes which changes must be applied to the database. Every time we need to create a database based on the model described by Python classes, we use migration.

The data may come as Python objects, dictionaries, or lists. This time we'll represent the entities from the database using Python classes that are located in the models directory.

Create migration for the app with one command:

python manage.py makemigrations dashboard

Here we specified that the app should tell Django to apply migrations for the dashboard app's models.

After creating a migration file, apply migrations described in it and create a database:

python manage.py migrate dashboard

If you see a new file db.sqlite3 in the project's directory, we are ready to work with the database.

Let's create instances of our Order class. For this, we'll use the Django shell - it's similar to the Python shell but allows accessing the database and creating new entries.

So, start the Django shell:

python manage.py shell

And write the following code in the interactive console:

from dashboard.models import Order>>> o1 = Order(... product_category='Books',... payment_method='Credit Card',... shipping_cost=39,... unit_price=59... )>>> o1.save()

Similarly, you can create and save as many objects as you need.

Connecting data to Flexmonster


And here's what I promised to explain.

Let's figure out how to pass the data from your model to the data visualization tool on the front end.

To make the back end and Flexmonster communicate, we can follow two different approaches:

  • Using the request-response cycle. We can use Python and the Django template engine to write JavaScript code directly in the template.
  • Using an async request (AJAX) that returns the data in JSON.

In my mind, the second one is the most convenient because of a number of reasons. First of all, Flexmonster understands JSON. To be precise, it can accept an array of JSON objects as input data. Another benefit of using async requests is the better page loading speed and more maintainable code.

Let's see how it works.

Go to the templates/dashboard_pivot.html.

Here we've created two div containers where the pivot grid and pivot charts will be rendered.

Within the ajax call, we make a request based on the URL contained in the data-URL property. Then we tell the ajax request that we expect a JSON object to be returned (defined by dataType).

Once the request is completed, the JSON response returned by our server is set to the data parameter, and the pivot table, filled with this data, is rendered.

The query result (the instance of JSONResponse) returns a string that contains an array object with extra meta information, so we should add a tiny function for data processing on the front end. It will extract only those nested objects we need and put them into a single array. This is because Flexmonster accepts an array of JSON objects without nested levels.

(Video) Django Plotly Dash Tutorial How to Connect Dashboards & Graphs into a Python Full Stack Application

function processData(dataset) { var result = [] dataset = JSON.parse(dataset); dataset.forEach(item => result.push(item.fields)); return result;}

After processing the data, the component receives it in the right format and performs all the hard work of data visualization. A huge plus is that there’s no need to group or aggregate the values of objects manually.

Here's how the entire script in the template looks:

function processData(dataset) { var result = [] dataset = JSON.parse(dataset); dataset.forEach(item => result.push(item.fields)); return result;}$.ajax({ url: $("#pivot-table-container").attr("data-url"), dataType: 'json', success: function(data) { new Flexmonster({ container: "#pivot-table-container", componentFolder: "https://cdn.flexmonster.com/", width: "100%", height: 430, toolbar: true, report: { dataSource: { type: "json", data: processData(data) }, slice: {} } }); new Flexmonster({ container: "#pivot-chart-container", componentFolder: "https://cdn.flexmonster.com/", width: "100%", height: 430, //toolbar: true, report: { dataSource: { type: "json", data: processData(data) }, slice: {}, "options": { "viewType": "charts", "chart": { "type": "pie" } } } }); }});

Don't forget to enclose this JavaScript code in <script> tags.

Phew! We’re nearly there with this app.

Fields customization


Flexmonster provides a special property of the data source that allows setting field data types, custom captions, and defining multi-level hierarchies.

This is a nice feature to have - we can elegantly separate data and its presentation right in the report's configuration.

Add it to the dataSource property of the report:

mapping: { "product_category": { "caption": "Product Category", "type": "string" }, "payment_method": { "caption": "Payment Method", "type": "string" }, "shipping_cost": { "caption": "Shipping Cost", "type": "number" }, "unit_price": { "caption": "Unit Price", "type": "number" }}

Dashboard's design


To make the dashboard, we’ve rendered two instances of Flexmonster (you can create as many as you want, depending on the data visualization goals you want to reach). One is for the pivot table with summarized data, and the other is for the pivot charts.

Both instances share the same data source from our model. I encourage you to try making them work in sync: with the reportchange event, you can make one instance react to the changes in another one.

You can also redefine the ‘Export’ button’s functionality on the Toolbar to make it save your reports to the server.

Results

Let’s start the Django development server and open http://127.0.0.1:8000/dashboard/ to see the resulting dashboard:

How to create an analytics dashboard in a Django app (4)

Looks nice, doesn't it?

Feedback

This time we learned how to create a simple Django app and display the data on the client side in the form of an analytics dashboard.

I do hope you enjoyed the tutorial!

Please leave your comments below - any feedback on the code’s improvement is highly appreciated.

References

The source code for the tutorial can be found on GitHub.

And here’s the project with Flexmonster & Django integration that inspired me for this tutorial.

Further, I recommend walking through important concepts in the documentation to master Django:

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

(Video) Data Dashboard App in Django || Tutorial 2020 || Adding Graphs || World Map

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

How to create an analytics dashboard in a Django app (5)
Veronika Rovnik

Excited about data science and data analysis projects.

If you read this far, tweet to the author to show them you care.

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

ADVERTISEMENT

(Video) COVID-19 ANALYTICS DASHBOARD (DJANGO & VUE)

FAQs

How to create Django custom dashboard? ›

As mentioned above, the first step is to create a template directory:
  1. # Django Root Project <-- you are here mkdir -p templates/ ...
  2. # YOU should be in the ROOT project $ pip install git+https://github.com/app-generator/django-admin-black.git $ # or $ easy_install git+https://github.com/app-generator/django-admin-black.git.
Nov 15, 2020

Can we create dashboard using Django? ›

Django Volt Bootstrap 5

Volt Dashboard is a free and open-source Bootstrap 5 Admin Dashboard featuring over 100 components, 11 example pages, and 3 plugins with Vanilla JS. There is more than 100 free Bootstrap 5 components included some of them being buttons, alerts, modals, date pickers, and so on.

How to add analytics in Django? ›

Installation
  1. Install django-google-analytics-app from PyPI or add to your Python path some other way.
  2. Add google_analytics to your INSTALLED_APPS setting.
  3. Add URL include to your project's urls.py file: re_path('djga/', include('google_analytics.urls')),

What is the best tool to create a dashboard? ›

Some of the best free dashboard tools for visualizing your metrics and KPIs are Datapad, Grafana, Databox, Dasheroo, FineReport, Metabase, Google Data Studio, Matomo, Tableau, and Inetsoft.

Can I use Python to create dashboard? ›

Panel is an open-source Python library that lets you create custom interactive web apps and dashboards by connecting user-defined widgets to plots, images, tables or text.

What should an analytics dashboard contain? ›

A web analytics dashboard gathers all the important metrics about your website traffic into a single custom dashboard. This dashboard shows you KPIs like: Page views, bounce rate, pages per session. Goal completions, such as form fills, lead generation, or sales conversions.

What is an example of an analytical dashboard? ›

Examples of Analytical dashboards include: Comparing Sales trends over time and forecasting. Digital Marketing dashboards that measure campaign performance.

Is Django useful for data analyst? ›

Django is a batteries included web framework that allows you to quickly build Web apps, Jupyter is an interact programming environment that gives us tools to more easily visualise data. They are both useful for data science but in completely different ways.

Can I build a CMS with Django? ›

The django CMS is an easy to use, open-source content management build using Django/Python. It is a great option for new developers who wish to create a site that tailors to their needs. The user-friendly interface is aimed at developers and content editors.

Is NASA using Django? ›

5. NASA. The website of the United States National Aeronautics and Space Administration (NASA) is built using Django. According to Semrush, in July 2022, the number of monthly website users has exceeded 82 million.

What does {% %} do in Django? ›

{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.

What does {% include %} does Django? ›

The include tag allows you to include a template inside the current template. This is useful when you have a block of content that is the same for many pages.

How do I add analytics to my app? ›

Follow these steps to enable install tracking in your Analytics account:
  1. Sign in to Google Analytics..
  2. Click Admin, and navigate to the property you want to edit.
  3. In the PROPERTY column, click Property Settings.
  4. In the iOS Campaign Tracking section, click the toggle to turn it ON.
  5. Click Save.

What are the 3 layers of dashboards? ›

A dashboard can also be segregated into three different informational layers: Monitoring information utilizing graphical, metrics data for executives. Analysis information utilizing summarized, dimensional data for analysts.

What are the three types of dashboards? ›

Types of dashboards (and how to choose the right one for you) There are three types of dashboards: operational, strategic, and analytical.

What does a good dashboard look like? ›

Great dashboards are clear, interactive, and user-friendly. They need to communicate information at a glance through efficient data visualizations that will enable users to extract actionable insights, identify trends and patterns, and find improvement opportunities through a friendly online data analysis process.

How do you build a successful dashboard? ›

Most of the time, you're going to be using a combination of numbers, bars, lines and tables and not much else.
  1. Group your related metrics. ...
  2. Be consistent. ...
  3. Use size and position to show hierarchy. ...
  4. Give your numbers context. ...
  5. Use clear labels your audience will understand. ...
  6. Remember it's for people. ...
  7. Keep evolving your dashboards.

Are dashboards outdated? ›

But why are dashboards 'dying'?

The complexity and volume of data in the digital era is constantly incoming and growing. Unfortunately, dashboards alone can't keep track of every important metric or part of the modern-day business, and manual analysis on its own isn't reliable or as efficient.

How do I create an interactive dashboard? ›

How to Create an Interactive Excel Dashboard
  1. Organize Your Source Data and Create a Layout. ...
  2. Build PivotTables to Organize Your Data. ...
  3. Apply Appropriate Formulae. ...
  4. Use Visual Elements, Charts, and Graphs. ...
  5. Add Interactive Settings and Tabs.
Sep 21, 2022

How do you visualize data in dashboard? ›

A data visualization dashboard provides decision makers with a high-level view of their most important metrics. It combines numbers, charts, graphs, and other graphics designed to focus an audience on the metrics that matter.

Which tool is best for data visualization? ›

The Best Data Visualization Software of 2023
  • Microsoft Power BI: Best for Business Intelligence.
  • Tableau: Best for Interactive Charts.
  • Qlik Sense: Best for Artificial Intelligence.
  • Klipfolio: Best for Custom Dashboards.
  • Looker: Best for Visualization Options.
  • Zoho Analytics: Best for Zoho Users.
  • Domo: Best for Custom Apps.
Jan 10, 2023

What 5 key metrics would you want to display on a data dashboard? ›

Here are a few key Sales Dashboard metrics to give you a fair idea: Lead Conversion Ratio. Customer Acquisition Cost (CAC)
...
  • Lead Conversion Ratio. ...
  • Customer Acquisition Cost (CAC) ...
  • Customer Churn Rate. ...
  • Customer Lifetime Value (LTV) ...
  • Number of Sales Opportunities. ...
  • Sales Target. ...
  • Sales Growth.
Dec 30, 2021

What are the four key elements of dashboard reporting? ›

Four Essential Phases of a Successful Marketing Dashboard
  • Step 1: Planning. During the Planning phase, you and your team will determine key factors to guide the discovery and design phases.
  • Step 2: Data Discovery. ...
  • Step 3: Design. ...
  • Step 4: Implementation.
Mar 1, 2016

What are the three core elements of analytics? ›

There are three types of analytics that businesses use to drive their decision making; descriptive analytics, which tell us what has already happened; predictive analytics, which show us what could happen, and finally, prescriptive analytics, which inform us what should happen in the future.

What are the 5 types of dashboards? ›

That being said, in this post, we will explain what is a dashboard in business, the features of strategic, tactical, operational, and analytical dashboards, and expound on examples that these different types of dashboards can be used. Let's get started.

What is the difference between dashboard and analytics? ›

Analytics Answers the “Why Behind the What”

So if dashboards answer the “what,” then analytics answer the “why” behind the what. Analytics take it a step further, digging down deeper into the data. We might pose analytics questions like: “When users search my site, what are the solid business outcomes/conversions?”

What is the average salary of Django developer? ›

Average Annual Salary by Experience

Django Developer salary in India with less than 1 year of experience to 4 years ranges from ₹ 1.2 Lakhs to ₹ 8.5 Lakhs with an average annual salary of ₹ 3 Lakhs based on 282 latest salaries.

Do professionals use Django? ›

Django is a Python-based web framework giving developers the tools they need for rapid, hassle-free development. You can find that several major companies employ Django for their development projects. Here are 9 global companies using Django: Instagram.

Is Django enough to get a job? ›

Yes. People have been using Django development to earn a living. So, if you intend to find a job as a Python Web Developer, the recommendation is to choose Django. The explosion of machine learning and 'Big Data' led to Python developers becoming even more popular.

Is Django good for CMS? ›

A CMS built for developers

Its lightweight core makes it easy to integrate with other software and put to use immediately, while its ease of use makes it the go-to choice for content managers, content editors and website admins.

What are two disadvantages to using the CMS? ›

Drawbacks
  • A CMS poses a larger Security Risk unless maintained and regularly updated. ...
  • The need to have qualified technicians maintain and upgrade software, means that maintenance of content management systems can get expensive.
  • You must learn the CMS. ...
  • You will need to set aside the man power for updating your website.

Is it hard to create a CMS? ›

Building a content management system can seem like a daunting task to the novice PHP developer. However, it needn't be that difficult. In this tutorial I'll show you how to build a basic, but fully functional, CMS from scratch in just a few hours. Yes, it can be done!

Do Google hire Django developers? ›

A computer scientist or someone otherwise proficient in programming practices and problem solving may get a job at Google. Django -- and your proficiency therein -- means next-to-nothing unless you're applying at a Django-specific workplace.

What is the disadvantage of Django? ›

Not for smaller projects. All the functionality of Django comes with lots of code. It takes server's processing and time, which poses some issues for low-end websites which can run on even very little bandwidth.

Is Django good for beginners? ›

Django is not a programming language; it is a coding framework built to be compatible with Python — which is a back end coding language. Learning Django can be immensely beneficial for anyone aspiring to become a programmer or web developer.

Why is Django so popular? ›

Django uses a “shared-nothing” architecture, which means that each part of the architecture is independent of the others. This makes it simple to replace or add hardware at any level, such as more database servers or web application servers, to cope with an increase in users.

Is Django a full stack? ›

Described on Python's official website as “the web framework for perfectionists (with deadlines)”, Django is a full-stack framework for web developers working with Python.

How to create a Django admin dashboard? ›

Install Django inside a clean virtual environment: $ python -m pip install django $ django-admin startproject School $ cd School $ ./manage.py startapp core $ ./manage.py migrate $ ./manage.py createsuperuser Username: admin Email address: admin@example.com Password: Password (again):

Can I create a dashboard with Python? ›

Panel is an open-source Python library that lets you create custom interactive web apps and dashboards by connecting user-defined widgets to plots, images, tables or text.

Can you build a dashboard in Python? ›

Dash is a free Python library built by the same company that created the plotly graphing library. With Dash, you can develop web-based, customizable, interactive dashboards, all in Python, without writing HTML or JavaScript. Each Dash app has two main parts: layout: determines what the Dash app looks like.

Videos

1. How to Create a Beautiful Python Visualization Dashboard With Panel/Hvplot
(Thu Vu data analytics)
2. Custom Analytics // Django Tutorial // Data Collection
(CodingEntrepreneurs)
3. 51 - My Finances App: Dashboards Part 1 - Django | DRF | React w. Data Analysis
(Sugarloaf And a Cup of Joe)
4. Google analytics Django website integration
(Zhang Shade)
5. Turn An Excel Sheet Into An Interactive Dashboard Using Python (Streamlit)
(Coding Is Fun)
6. Data visualization : interactive website django 📊 | PowerAI
(Semah Kadri)

References

Top Articles
Latest Posts
Article information

Author: Chrissy Homenick

Last Updated: 10/14/2023

Views: 6133

Rating: 4.3 / 5 (54 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Chrissy Homenick

Birthday: 2001-10-22

Address: 611 Kuhn Oval, Feltonbury, NY 02783-3818

Phone: +96619177651654

Job: Mining Representative

Hobby: amateur radio, Sculling, Knife making, Gardening, Watching movies, Gunsmithing, Video gaming

Introduction: My name is Chrissy Homenick, I am a tender, funny, determined, tender, glorious, fancy, enthusiastic person who loves writing and wants to share my knowledge and understanding with you.