top of page
Abdul Wahith

Combining Django Templates with React for Interactive Webpages


Learn how to integrate Django templates with React to build interactive and dynamic webpages. This guide covers setting up Django and React projects, serving React components through Django templates, handling data with Django REST framework, and creating interactive web applications.


In modern web development, combining the power of Django's backend with React's dynamic frontend capabilities can lead to highly interactive and efficient web applications. This blog will guide you through the process of integrating Django templates with React to create interactive and dynamic webpages.


Introduction

Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. React is a JavaScript library for building user interfaces, particularly single-page applications where data changes over time. Combining these two technologies allows you to leverage Django's robust backend and React's dynamic frontend capabilities.


Setting Up the Django Project

First, let's set up a new Django project. Make sure you have Django installed in your environment. If not, you can install it using pip:


pip install django

Create a new Django project and navigate into it:


django-admin startproject myproject
cd myproject

Create a new Django app:


python manage.py startapp myapp

Add myapp to the INSTALLED_APPS list in myproject/settings.py.


Setting Up the React Project

Next, we'll set up a new React project inside our Django project directory. Navigate to the project root and run the following commands:


npx create-react-app frontend
cd frontend
npm start

This will create a new React application and start the development server.


Integrating React with Django

To integrate React with Django, we need to build the React app and serve the built files through Django. First, build the React app:


npm run build

This will create a build directory inside the frontend folder with static files. Next, we need to configure Django to serve these static files.


In myproject/settings.py, add the following configurations:



import os

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'frontend/build/static'),
]

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'frontend/build')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                ...
            ],
        },
    },
]

In myproject/urls.py, configure the URL patterns to serve the React app:



from django.urls import path
from django.views.generic import TemplateView

urlpatterns = [
    path('', TemplateView.as_view(template_name='index.html')),
]

Serving React Components in Django Templates

To render React components within Django templates, we need to ensure that Django serves the React build files correctly. Create a base template in myapp/templates/myapp/index.html:



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Django React App</title>
    {% load static %}
    <link rel="stylesheet" href="{% static 'css/main.css' %}">
</head>
<body>
    <div id="root"></div>
    <script src="{% static 'js/main.js' %}"></script>
</body>
</html>

Ensure the index.html file in frontend/public matches the Django template structure if necessary. Django will now serve the React app from the build directory.


Handling Data with Django and React

To handle data between Django and React, we can use Django's REST framework to create API endpoints and fetch data in React using axios or the built-in fetch API.


Install Django REST framework:


pip install djangorestframework

Add rest_framework to the INSTALLED_APPS list in myproject/settings.py.


Create a serializer in myapp/serializers.py:



from rest_framework import serializers
from .models import MyModel

class MyModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = MyModel
        fields = '__all__'

Create an API view in myapp/views.py:


from rest_framework import viewsets
from .models import MyModel
from .serializers import MyModelSerializer

class MyModelViewSet(viewsets.ModelViewSet):
    queryset = MyModel.objects.all()
    serializer_class = MyModelSerializer

Add the API endpoint to myapp/urls.py:


from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import MyModelViewSet

router = DefaultRouter()
router.register(r'mymodel', MyModelViewSet)

urlpatterns = [
    path('api/', include(router.urls)),
]

In React, fetch the data from the Django API:


import React, { useEffect, useState } from 'react';
import axios from 'axios';

const MyComponent = () => {
  const [data, setData] = useState([]);

  useEffect(() => {
    axios.get('/api/mymodel/')
      .then(response => {
        setData(response.data);
      })
      .catch(error => {
        console.error('There was an error fetching the data!', error);
      });
  }, []);

  return (
    <div>
      <h1>Data from Django API</h1>
      <ul>
        {data.map(item => (
          <li key={item.id}>{item.name}</li>
        ))}
      </ul>
    </div>
  );
};

export default MyComponent;

Building an Interactive Webpage

Now that we have integrated Django with React and handled data fetching, we can build a more interactive webpage. For example, we can add forms, dynamic content updates, and other interactive elements using React components while leveraging Django's powerful backend capabilities.


Conclusion

Combining Django templates with React allows you to create highly interactive and dynamic webpages. By leveraging Django's robust backend and React's dynamic frontend capabilities, you can build efficient and modern web applications. This integration provides the best of both worlds: Django's ease of use and rapid development with React's flexibility and interactivity.

13 views0 comments

Comments


bottom of page