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 serverwhile 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.

17 thoughts on “Integrate Plotly Dash in Django”

  1. Hi Anindya ,
    I am trying to follow step by step your example to lear how to integrate dash in django and i get the following error when I press the Dash Plots button:
    ———————————————————————————————————–
    expected string or bytes-like object

    Request Method: GET
    Request URL: http://127.0.0.1:8000/dash_plot
    Django Version: 2.2.6
    Exception Type: TypeError
    Exception Value:

    expected string or bytes-like object

    Exception Location: /usr/lib/python3.8/textwrap.py in dedent, line 430
    Python Executable: /home/ramona/VirtEnv/bin/python
    Python Version: 3.8.2
    Python Path:

    [‘/home/ramona/Escritorio/django_dash’,
    ‘/usr/lib/python38.zip’,
    ‘/usr/lib/python3.8’,
    ‘/usr/lib/python3.8/lib-dynload’,
    ‘/home/ramona/VirtEnv/lib/python3.8/site-packages’,
    ‘/home/ramona/VirtEnv/lib/python3.8/site-packages/IPython/extensions’]

    Server time: Fri, 18 Sep 2020 10:10:54 +0000
    Error during template rendering

    In template /home/ramona/Escritorio/django_dash/templates/dash_plot.html, error at line 12
    expected string or bytes-like object
    2
    3
    4
    5 Plotly in Django
    6
    7
    8
    9
    10 {% if user.is_authenticated %}
    11
    12 {% plotly_app name=’dash_integration_id’ ratio=0.45 %}
    13
    14
    15 {% else %}
    16
    17 You are not logged in
    18 Please login to view plots
    19
    20
    21 login
    22
    ———————————————————————————————————–
    Could you please help me with that? Thank you very much

  2. I had the same error as Ramona (‘expected string or bytes-like object’). I was unable to install the exact same versions as mentioned in the article since pip complained about incompalilities between the packages. However, I now have the example running with these versions:

    django==2.2
    django_plotly_dash==1.1.4
    channels==2.4.0
    bootstrap4==0.1.0
    dpd_static_support==0.0.5
    dash==1.6.1
    dash_daq==0.3.1
    dash_bootstrap_components==0.7.2
    whitenoise==5.0.1
    pandas==1.1.3

    My Python version is 3.8.3.

  3. Настоящий секс по телефону – 8-809-505-6673! https://sexcall.online/ Платы за межгород нет! Круглосуточно! 100% конфиденциально! Абсолютно легально, честно, без подписок, обмана и скрытых платежей! И самое главное – никаких запретов и ограничений! Любые сексуальные фантазии

  4. Список лучших бездепозитных бонусов за регистрацию с выводом для новых игроков из России и с других стран СНГ. Вам не обязательно тратить время на поиск бонусов без депозита или фриспинов за регистрацию на других сайтах и форумах. Подробную информацию о лучших бездепозитных бонусах казино РФ, Вы найдёте на сайте – https://all.casino-profit.pro/casino/rub.html

  5. Преимущества онлайн казино очевидны для всех, кто хотя бы раз пробовал играть в онлайн-казино. Мы собрали лучшие бездепозитные бонусы за регистрацию, фриспины и другие акции и бонусы казино 2020 года в одном месте. Начните зарабатывать играя, посетив сайт – https://all.casino-profit.pro/nodep-bonuses.html

Leave a Comment

Your email address will not be published. Required fields are marked *