4 Apr 2020

Integrate Plotly Dash in Django


As we know Plotly Dash is most popular framework to build interactive dashboard in python. You can use Dash if want to build web application specifically for interactive dashboard.

But if you want to build a web application and you want to serve other things (like video, music etc.) along with interactive dashboard then you have to choose some other framework in Python.

Django is most popular framework in python to build such kind of complex web application.

In this tutorial I will show you how to integrate Plotly Dash in Django.

For this tutorial I will be using python library called django_plotly_dash to integrate Plotly Dash in Django.


Also Read:

Prerequisites

While writing this tutorial below were my Python version:

  • Python: 3.6.3

To integrate Plotly Dash on Django using django_plotly_dash you need some additional libraries. To install those additional libraries with specific version, type below commands in cmd:

pip install django==2.1.5
pip install django_plotly_dash==1.1.4
pip install --user channels
pip install --user bootstrap4
pip install --user dpd_static_support==0.0.5
pip install dash==1.4.1
pip install dash_daq==0.3.1
pip install dash_bootstrap_components==0.7.2
pip install whitenoise==5.0.1

Now let’s start setting up a Django project to test one Django Plotly Dash example. 

This article will be easy for you if you have some basic knowledge in Django. Though I will explain everything basic level.

Django Project Setup

Type below command in cmd to create a Django project.
django-admin startproject django_dash
Note: Giving my project name django_dash
Now inside main project folder create another folder called templates and follow steps mentioned below.
1.    Create a HTML file named home.html (sharing code below). This is home page of our web application.

2.    Create a HTML file named dash_plot.html (sharing code below). This page is to show dashboard/ visualization built by Plotly Dash.


3.    Create another folder inside ‘templates’ folder named registration

4.    Inside ‘registration’ folder create another HTML file named login.html (sharing code below)
So now folder structure for entire project should looks like below:
django_dash
├── templates
|   ├── home.html
|   ├── dash_plot.html
|   ├── registration
|         └── login.html
├── django_dash
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
└── manage.py

Relate Article

home.html


dash_plot.html

In this code line number 12 to connect Plotly Dash with Django by ID

login.html


Now inside django_dash (application folder) folder you need to do below things
1.    Edit settings.py
2.    Edit urls.py
3.    Create a python file named routing.py
4.    Create a python file named dash_app_code.py
So now folder structure for entire project should looks like below:
django_dash
├── templates
|   ├── home.html
|   ├── dash_plot.html
|   ├── registration
        └── login.html
├── django_dash
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
  ├── routing.py
  ├── dash_app_code.py
│   └── wsgi.py
└── manage.py


Django Plotly Dash edit settings.py

In settings.py you need to add two things (listed below)
1.    Add template folder address inside TEMPLATES list dictionary (inside DIR key). By default it will be like: 'DIRS': [],

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates'),],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

2.    Add below lines/ scripts at the end of settings.py

# ---------- Add Django Dash start --------------------------------

# Adding ASGI Application
ASGI_APPLICATION = 'django_dash.routing.application'

#

# To use home.html as default home page
LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = 'home'

# Define folder location of 'static' folder
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

# 'django_dash': django app name
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'django_dash', 'static'),
    ]

# Static content of Plotly components that should
# be handled by the Django staticfiles infrastructure

PLOTLY_COMPONENTS = [
    'dash_core_components',
    'dash_html_components',
    'dash_bootstrap_components',
    'dash_renderer',
    'dpd_components',
    'dpd_static_support',
]

# Staticfiles finders for locating dash app assets and related files (Dash static files)

STATICFILES_FINDERS = [

    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',

    'django_plotly_dash.finders.DashAssetFinder',
    'django_plotly_dash.finders.DashComponentFinder',
    'django_plotly_dash.finders.DashAppDirectoryFinder',
]

# Channels config, to use channel layers

CHANNEL_LAYERS = {
    'default': {
        'BACKEND': 'channels_redis.core.RedisChannelLayer',
        'CONFIG': {
            'hosts': [('127.0.0.1', 6379),],
        },
    },
}


Sharing full settings.py code for your reference


settings.py



Django Plotly Dash edit urls.py

Copy and paste below code to your urls.py (After removing everything from urls.py)


Create a python file named routing.py

Create a python file named routing.py inside django_dash (application folder) folder and write/paste below one line code into it. Repeating again to confirm that it is just one line of code.

from django_plotly_dash.routing import application

This routing.py code is necessary for ASGI server while connecting/ showing Plotly Dash in Django. Otherwise you will end up with error saying:

raise ImproperlyConfigured("Cannot import ASGI_APPLICATION module %r" % path)
django.core.exceptions.ImproperlyConfigured: Cannot import ASGI_APPLICATION module 'django_dash.routing'

Create a python file named dash_app_code.py

Create a python file named dash_app_code.py inside django_dash (application folder) folder and write below code into it.
This code is just a Plotly Dash code to make interactive dashboard
In this code line number 14 is important. This line is to define Id for Plotly Dash integration with Django.

dash_app_code.py



Once you are done with above steps successfully, run below commands in cmd to migrate

python manage.py migrate

Then run Django server by executing below command in cmd
python manage.py runserver

Now you are done with the complete Django Plotly Dash example web application.
Open http://127.0.0.1:8000/ in your web browser to see and use that complete Django Plotly Dash example web application.

But you can’t use this application right now, as I have included authentication system to use this Plotly Dash with Django application.

You can’t login now as you don’t have or you have not created any authenticated user name with password till now for this project.

Follow my previous article to create user to login.


Conclusion

In this Django Plotly Dash tutorial I have shown you how to Connect Dashboards & Graphs made by Plotly Dash into a Django web application using Python library called django_plotly_dash.

Now in this tutorial I have shown everything webpage. To make this same Django Plotly Dash web application attractive, check out my previous page: Django stylish login logout tutorial.

If you have any question or suggestion regarding this topic see you in comment section. I will try my best to answer.