Build a Analytics Dashboard in Streamlit with Django and Django Rest framework
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
-
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
-
Create a Django Project:
- Start a new Django project:
django-admin startproject myproject
- Navigate to your project directory:
cd myproject
- Start a new Django project:
-
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', ]
- Create a new app within your project:
Step 2: Create a REST API with DRF
-
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)
- In
-
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__'
- Create a serializer in
-
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
- Create views in
-
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
.
- In
Step 3: Build the Streamlit Dashboard
-
Create a New Streamlit App:
- Create a new Python file for your Streamlit application, e.g.,
app.py
.
- Create a new Python file for your Streamlit application, e.g.,
-
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()
- Use the requests library to fetch data from your Django backend:
-
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)
- Use Streamlit’s built-in functions to create charts:
-
Customize Layout:
- Use Streamlit’s layout options to arrange your dashboard components:
st.title("Analytics Dashboard") st.sidebar.header("Settings")
- Use Streamlit’s layout options to arrange your dashboard components:
Step 4: Handle User Inputs and Session State
-
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
- Use Streamlit forms to allow users to submit data:
-
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!