Build a Analytics Dashboard in Streamlit with Django and Django Rest framework

4 min read 6 hours ago
Published on Dec 23, 2024 This response is partially generated with the help of AI. It may contain inaccuracies.

Table of Contents

Introduction

In this tutorial, you will learn how to build an analytics dashboard using Django, Django Rest Framework (DRF), and Streamlit. This setup is particularly useful for data science and machine learning applications, allowing you to create interactive and visually appealing dashboards. You will explore essential functionalities such as creating charts, customizing layouts, managing session states, and handling data transactions between the frontend and backend.

Step 1: Set Up Your Development Environment

  1. Install Required Software:

    • Ensure you have Python installed on your system. Use version 3.6 or above.
    • Install Django and Django Rest Framework, if you haven't already:
      pip install django djangorestframework
      
    • Install Streamlit:
      pip install streamlit
      
  2. Create a Django Project:

    • Start a new Django project:
      django-admin startproject myproject
      
    • Navigate to your project directory:
      cd myproject
      
  3. Create a Django App:

    • Create a new app within your project:
      python manage.py startapp analytics
      
    • Add the app to your project settings in settings.py:
      INSTALLED_APPS = [
          ...
          'analytics',
          'rest_framework',
      ]
      

Step 2: Create a REST API with DRF

  1. Define Your Models:

    • In analytics/models.py, define the models that will hold your data. For example:
      from django.db import models
      
      class DataPoint(models.Model):
          value = models.FloatField()
          timestamp = models.DateTimeField(auto_now_add=True)
      
  2. Create Serializers:

    • Create a serializer in analytics/serializers.py:
      from rest_framework import serializers
      from .models import DataPoint
      
      class DataPointSerializer(serializers.ModelSerializer):
          class Meta:
              model = DataPoint
              fields = '__all__'
      
  3. Set Up Views:

    • Create views in analytics/views.py to handle API requests:
      from rest_framework import viewsets
      from .models import DataPoint
      from .serializers import DataPointSerializer
      
      class DataPointViewSet(viewsets.ModelViewSet):
          queryset = DataPoint.objects.all()
          serializer_class = DataPointSerializer
      
  4. Configure URLs:

    • In analytics/urls.py, set up the API routes:
      from django.urls import path, include
      from rest_framework.routers import DefaultRouter
      from .views import DataPointViewSet
      
      router = DefaultRouter()
      router.register(r'datapoints', DataPointViewSet)
      
      urlpatterns = [
          path('', include(router.urls)),
      ]
      
    • Include these URLs in your project’s main urls.py.

Step 3: Build the Streamlit Dashboard

  1. Create a New Streamlit App:

    • Create a new Python file for your Streamlit application, e.g., app.py.
  2. Fetch Data from Django API:

    • Use the requests library to fetch data from your Django backend:
      import streamlit as st
      import requests
      
      @st.cache
      def load_data():
          response = requests.get('http://127.0.0.1:8000/api/datapoints/')
          return response.json()
      
      data = load_data()
      
  3. Display Data in Charts:

    • Use Streamlit’s built-in functions to create charts:
      import pandas as pd
      import altair as alt
      
      df = pd.DataFrame(data)
      chart = alt.Chart(df).mark_line().encode(
          x='timestamp',
          y='value'
      )
      st.altair_chart(chart, use_container_width=True)
      
  4. Customize Layout:

    • Use Streamlit’s layout options to arrange your dashboard components:
      st.title("Analytics Dashboard")
      st.sidebar.header("Settings")
      

Step 4: Handle User Inputs and Session State

  1. Create Forms for User Inputs:

    • Use Streamlit forms to allow users to submit data:
      with st.form(key='data_form'):
          value = st.number_input('Enter a data point')
          submit_button = st.form_submit_button(label='Submit')
          if submit_button:
              # Code to send data to the server
      
  2. Manage Session State:

    • Use Streamlit's session state to maintain user inputs or selections across different interactions.

Conclusion

In this tutorial, you learned how to set up an analytics dashboard using Django, Django Rest Framework, and Streamlit. You created a REST API for data management, built a Streamlit application to visualize data, and implemented user interaction features. As next steps, consider exploring additional visualization options in Streamlit, enhancing your API with authentication, or deploying your application using services like Heroku or AWS. Happy coding!