Plot your data in your Django web application with Plotly (Part 1).

P4k D3velopers
Django Unleashed
Published in
5 min readMar 25, 2024
Plotly and Django logos.

Hi Medium readers!

Today in this article we’ll create a very simple Django project to learn how to easily embed a plot from Plotly in an HTML tag to show it in our Django web application view.

The steps we’ll follow in this part will be the next:

  • Install Plotly library.
  • Create a Django application.
  • How to easily embed plot from Plotly to in an HTML tag.
  • Display Plotly plot in our Django web application view.

I’ll not pay too much attention into install Django and create a project.

If you want more detailed information about the project configuration and structure, you can read in 3min my first article and in 5 min the second one in the next links:

Install Plotly

What is Plotly? Is an amazing Python’s library to create interactive plots.

Plotly introduced web-based data visualization to Python and today, the company offers Dash Enterprise, which provides the best software tools and platform to enable every enterprise in the world to build and scale data applications quickly and easily.

Also the interactive plots created with Plotly, comes with some tools to interact with plot like: zoom in, zoom out pan, download, box select among others.

Plotly tools to interact with the plot.

The Plotly Python library is an interactive, open-source plotting library that supports over 40 unique chart types covering a wide range of statistical, financial, geographic, scientific, and 3-dimensional use-cases.

Install Plotly is very easy. To install the latest version type the next command:

pip install plotly==5.20.0

With this we are ready to import Plotly to our Python files, so also in our Django project.

Create Django project

For the article aim, we’ll do a Body Mass Index (BMI) Calculator as a web application.

Easily create a project called ‘BMICalculator’, and an app inside called ‘BMIApp’.

  • Create the ‘BMICalculator’ project, and access to its folder:
django-admin startproject BMICalculator
cd BMICalculator
  • Start a ‘BMIApp application:
python3 manage.py startapp BMIApp
  • Add the ‘BMIApp’ application into the ‘BMICalculator installed apps settings, in the ‘settings.py’ file:
INSTALLED_APPS = [
'BMIApp.apps.BmiappConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
  • In the ‘views.py’ file create a very simple view to get the landing view:
from django.shortcuts import render

# Landing view
def index(request):
'''
Landing view for the BMI Calculator.
'''

if request.method == 'GET':

# Template context date
context: dict = { 'title': 'BMI Calculator'}

# Return view
return render(request, 'BMIApp/base.html', context)
  • Create the ‘static/BMIApp’ and ‘templates/BMIApp’ folders, for the static and template files, and create a ‘base.html’ file in the templates/BMIAppfolder, with a very simple view:
<!-- HEAD -->
<head>

<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-betal/dist/js/bootstrap.bundle.min.js"></script>
{% load static %}
<link rel="stylesheet" href="{% static 'BMIApp/css/index.css' %}">

</head>

<!-- BODY -->
<body>

<!-- Title -->
<h1 class="w-100 p-4 border-bottom text-center">{{title}}</h1>

<!-- Footer -->
<footer class="w-100 m-0 mt-4 p-4">
<div class="row ps-4 pe-4 text-end">
<span class="fs-6 text-info"><small>Developed by PAK</small></span>
</div>
</footer>

</body>
  • Create a ‘urls.py’ inside our ‘BMIApp’ foder including our landing view path:
from django.urls                import path, include
from django.conf import settings
from django.conf.urls.static import static
from . import views

app_name = 'BMIApp'

urlpatterns = [
path("accounts/", include("django.contrib.auth.urls")),

path('',
views.index,
name='index'),

path('BMIApp/',
views.index,
name='index')

] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
  • Add the ‘BMIApp’ application urls, to the ‘urls.py’ in the ‘BMICalculator’ folder:
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
path('admin/', admin.site.urls),
path('', include('BMIApp.urls')),
]
  • Place your command-line prompt into the ‘BMICalculator’ folder and migrate the project:
python manage.py migrate
  • And execute the application:
python3 manage.py runserver
  • Check the view:
BMI Calculator web application landing view.

Plotly to HTML tag

First of all let’s import the Plotly library i our ‘views.py’ file. We’ll use the express’, ‘offline’, ‘graph_objs’ modules:

import  plotly.express      as      px
from plotly.offline import plot
from plotly.graph_objs import Figure

Let’s create some sample data to see how simple it is to plot some data:

# Bar plot X axis values
x_values = ["Sample 1", "Sample 2", "Sample 3"],

# Bar plot Y axis values
y_values = [1, 3, 2]

Embed the plot to show it in a HTML tag. Plotly provide different ways to do this, but i like the way I shown you for its own simple way to do it.

# Create the plot
bar_plot = Figure(data=[go.Bar( x = x,
y = y,
textposition = 'auto',)])

# Embed the plot in an HTML div tag
bar_plot_div: str = plot(bar_plot, output_type="div")

Send the plot variable to the template by including it into the ‘context’ variable as we did with the application title:

# Template context date
context: dict = {'title': 'BMI Calculator',
'bar_plot': bar_plot_div}

# Return view
return render(request, 'BMIApp/base.html', context)

Add the entire plot into the template view. Don’t forget the ‘safe’ filter, if not the plot will not be visible:

<div class="row">
<div class="col-3"></div>
<div class="col-6">
{{bar_plot|safe}}
</div>
<div class="col-3"></div>
</div>

Lets re-execute our BMI Calculator application and check the landing view:

BMI Calculation landing view.

That was very easy! I hope it was helpful!

In the next article, we’ll focus on:

  • Make BMI Calculator work.
  • Record data.
  • Make data calculations.

Thanks for reading me!

Remember to clap the article if you liked!

--

--

P4k D3velopers
Django Unleashed

Writes about Python Web Development (Django/Flask) and Data Science (Python/pandas/statistics/) || Scientist || Prototype creator || Side hustles