React Flow makes it easy to build interactive node-based UIs, such as flowcharts and process diagrams, in React. Meanwhile, Django is a robust backend framework known for its scalability and simplicity in web development. Combining these two frameworks can unlock some serious functionality, enabling you to build rich, dynamic frontends while leveraging the security and backend capabilities of Django.
In this article, we will walk through how to embed a React Flow component within a Django application. By the end, you’ll know how to render a React Flow diagram on a Django page, and communicate data between the backend and frontend effectively.
Setting up the Django Project
First, make sure you have Django installed. If not, you can install it using:
pip install django
Create a new Django project and an app where you’ll embed your React frontend:
django-admin startproject flowchart_project
cd flowchart_project
django-admin startapp flowchart_app
In your flowchart_project/settings.py
, add 'flowchart_app'
to your INSTALLED_APPS
. This tells Django to recognize the app.
Configuring React in the Django App
React components can be integrated into Django by using Webpack or any frontend bundler to compile React and serve it as part of your Django templates. To set up React inside your Django app, follow these steps:
- Initialize the React Frontend: Inside your
flowchart_app
, create astatic
folder to store your React code:
mkdir -p flowchart_app/static/frontend
Inside this folder, you can initialize your frontend using the following commands:
npx create-react-app frontend
cd frontend
2. Install React Flow: You’ll need React Flow for the node-based UI. Install it using npm or yarn:
npm install reactflow
3. Add React Flow Component: Create a React component for your flowchart inside the src/components
directory of your frontend:
// flowchart_app/static/frontend/src/components/FlowChartComponent.js
import React from 'react';
import ReactFlow, { addEdge, Background, Controls, MiniMap, useNodesState, useEdgesState } from 'reactflow';
import 'reactflow/dist/style.css';
const initialNodes = [
{
id: '1',
type: 'input',
data: { label: 'Start Node' },
position: { x: 250, y: 5 },
},
{ id: '2', data: { label: 'Middle Node' }, position: { x: 100, y: 100 } },
{ id: '3', data: { label: 'End Node' }, position: { x: 400, y: 100 } },
];
const initialEdges = [{ id: 'e1-2', source: '1', target: '2' }, { id: 'e2-3', source: '2', target: '3' }];
const FlowChartComponent = () => {
const [nodes, setNodes, onNodesChange] = useNodesState(initialNodes);
const [edges, setEdges, onEdgesChange] = useEdgesState(initialEdges);
const onConnect = (params) => setEdges((eds) => addEdge(params, eds));
return (
<div style={{ height: 400 }}>
<ReactFlow
nodes={nodes}
edges={edges}
onNodesChange={onNodesChange}
onEdgesChange={onEdgesChange}
onConnect={onConnect}
>
<MiniMap />
<Controls />
<Background />
</ReactFlow>
</div>
);
};
export default FlowChartComponent;
4. Build the React App: To make React work with Django, you’ll need to build the React app. Run the following command inside the frontend
directory:
npm run build
This will generate static files that can be served in Django from the static/frontend/build
folder.
Serving React in a Django Template
Now that the React component is set up, you need to embed it in a Django template. First, make sure your Django app is configured to serve static files by adding these lines in your settings.py
:
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'flowchart_app/static/frontend/build')]
Next, create a template where you’ll load the React component:
<!-- flowchart_app/templates/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>React Flow in Django</title>
</head>
<body>
<div id="root"></div>
<script src="{% static 'static/js/bundle.js' %}"></script>
<script src="{% static 'static/js/1.chunk.js' %}"></script>
<script src="{% static 'static/js/main.chunk.js' %}"></script>
</body>
</html>
Routing in Django
Now, set up Django routing to render this template. In your views.py
file, add a simple view:
from django.shortcuts import render
def index(request):
return render(request, 'index.html')
In your urls.py
file, point the root URL to this view:
from django.urls import path
from .views import index
urlpatterns = [
path('', index, name='index'),
]
Final Touch: Handling Data Flow Between React and Django
One of the biggest strengths of using Django with React is the ability to pass data between the frontend and backend. You can use Django’s REST framework to build an API that interacts with React Flow, allowing for real-time updates and storage of the flowchart data.
Here’s an example API view to handle flow data:
from rest_framework.response import Response
from rest_framework.decorators import api_view
@api_view(['POST'])
def save_flow_data(request):
flow_data = request.data
# Process the flow data
return Response({"message": "Flow saved successfully!"})
In React, you can send a POST request to this endpoint when saving the flow:
const saveFlowData = async (flowData) => {
const csrfToken = getCSRFToken(); // CSRF token method in React
await fetch('/api/save-flow-data/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': csrfToken,
},
body: JSON.stringify(flowData),
});
};
Thank you for following along with this tutorial. We hope you found it helpful and informative. If you have any questions, or if you would like to suggest new Python code examples or topics for future tutorials/articles, please feel free to join and comment. Your feedback and suggestions are always welcome!
You can find the same tutorial on Medium.com.