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:


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:
├── templates
|   ├── home.html
|   ├── dash_plot.html
|   ├── registration
|         └── login.html
├── django_dash
│   ├──
│   ├──
│   ├──
│   └──
Relate Article



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


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

Django Plotly Dash edit

In 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’: [],
        ‘BACKEND’: ‘django.template.backends.django.DjangoTemplates’,
        ‘DIRS’: [os.path.join(BASE_DIR, ‘templates’),],
        ‘APP_DIRS’: True,
        ‘OPTIONS’: {
            ‘context_processors’: [
2.    Add below lines/ scripts at the end of
# ———- Add Django Dash start ——————————–
# Adding ASGI Application
ASGI_APPLICATION = ‘django_dash.routing.application’
# To use home.html as default home page
# Define folder location of ‘static’ folder
STATIC_ROOT = os.path.join(BASE_DIR, ‘staticfiles’)
# ‘django_dash’: django app name
    os.path.join(BASE_DIR, ‘django_dash’, ‘static’),
# Static content of Plotly components that should
# be handled by the Django staticfiles infrastructure
# Staticfiles finders for locating dash app assets and related files (Dash static files)
# Channels config, to use channel layers
    ‘default’: {
        ‘BACKEND’: ‘channels_redis.core.RedisChannelLayer’,
        ‘CONFIG’: {
            ‘hosts’: [(‘’, 6379),],
Sharing full code for your reference

Django Plotly Dash edit

Copy and paste below code to your (After removing everything from

Create a python file named

Create a python file named 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 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

Create a python file named 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.

Once you are done with above steps successfully, run below commands in cmd to migrate
python migrate
Then run Django server by executing below command in cmd
python runserver
Now you are done with the complete Django Plotly Dash example web application.
Open 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.


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.

39 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:
    Django Version: 2.2.6
    Exception Type: TypeError
    Exception Value:

    expected string or bytes-like object

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


    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
    5 Plotly in Django
    10 {% if user.is_authenticated %}
    12 {% plotly_app name=’dash_integration_id’ ratio=0.45 %}
    15 {% else %}
    17 You are not logged in
    18 Please login to view plots
    21 login
    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:


    My Python version is 3.8.3.

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

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

  5. Преимущества онлайн казино очевидны для всех, кто хотя бы раз пробовал играть в онлайн-казино. Мы собрали лучшие бездепозитные бонусы за регистрацию, фриспины и другие акции и бонусы казино 2020 года в одном месте. Начните зарабатывать играя, посетив сайт –

  6. Is there an alternative to specifying the plot ration in the html file? I want to make the plots responsive for mobile devices, is it possible to do so?

  7. Is there an alternative to specifying the plot ratio in the html file? I want to make the plots responsive for mobile devices, is it possible to do so?

  8. Как и обещал, запускаю конкурс на 10 призов по 0,001 BTC среди подписчиков! Подписывайся на канал – узнай условия и удачи!

  9. Элементы лестниц оптом, кухни на заказ, двери из массива дуба – На сайте большой выбор изделий из дерева (дуб, бук, ясень, береза, сосна): балясины для лестниц, перила для лестниц, ступени для лестниц, двери из массива дуба, мебельный щит! На рынке более 15 лет, отгружаем товар в любые регионы!

  10. You received a money transfer of $ 89.44! PREPAYMENT! To receive funds, go to the payment page
    [url=]Detail[/url]: [url=]Official bank site/url] Official bank site Official bank site

  11. ZandCell COVID-19 Saliva Antigen Test Nitrile gloves, FFP 2 Mask. Large wholesale, from a warehouse in Europe. All documents and certificates are available. Sending samples on request. Contract supplies for government and commercial organizations and individuals

  12. В Pinterest с 2012 г. Реклама в нем дает Заказчикам из Etsy, Shopify, amazon заработки от 7000 до 100 000 usd в месяц. Ручная работа, Цена 300-1000 usd за месяц

Leave a Comment

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