DEV Community

Cover image for Integrating Django and React in a Django Project
Akanmu Akinkunmi
Akanmu Akinkunmi

Posted on • Edited on

Integrating Django and React in a Django Project

If you're a developer working on a project that involves both Django and React, you might be wondering how to seamlessly integrate these technologies. Django is a powerful web framework for Python, while React is a popular JavaScript library for building user interfaces. Combining them can provide a robust solution for creating modern web applications. In this blog post, we'll explore a step-by-step guide on how to integrate a React project into a Django project.

Directory Structure

Assuming you have a Django project with the following directory structure:

project/

├── backend/
│ ├── manage.py
│ ├── backend/
│ │ ├── settings.py
│ │ └── ...
│ └── ...

└── frontend/
├── src/
│ └── ...
├── public/
│ └── index.html
└── ...

The Django project is in the backend directory, and the React project is in the frontend directory. Let's go through the integration process.

1. Building the React Project

Firstly, you need to build the React project. The script below, placed in your Django project's main file (e.g., manage.py), will handle this task for you:

#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import subprocess
import sys

def main():
    """Run administrative tasks."""
    BASE_DIR = os.path.dirname(os.path.abspath(__file__))

    # Assuming your ReactJS project is in the 'frontend' directory inside your Django project
    react_project_directory = os.path.join(BASE_DIR, 'frontend')

    subprocess.run(['npm', 'run', 'build'], cwd=react_project_directory, check=True)

    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings')
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)

if __name__ == '__main__':
    main()

Enter fullscreen mode Exit fullscreen mode

This script ensures that before running any Django command, the React project is built using the npm run build command.

2. Configuring Django Settings

In your Django project's settings.py, add the following configurations to serve static files:

settings.py

BASE_DIR = os.path.dirname(os.path.abspath(__file__))

STATICFILES_DIRS = [os.path.join(BASE_DIR, 'frontend/dist/assets')]
STATIC_URL = '/assets/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
Enter fullscreen mode Exit fullscreen mode

These settings define where Django should look for static files, the URL for serving them, and the directory where the collected static files should be stored.

3. Updating URL Patterns

Update your urls.py to include the necessary URL patterns:

#urls.py

from django.contrib import admin
from django.urls import path, re_path
from django.views.generic import TemplateView
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', TemplateView.as_view(template_name='index.html')),
]

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Enter fullscreen mode Exit fullscreen mode

This configuration ensures that Django serves the React application's entry point (index.html) when accessing the root URL.

Conclusion

By following these steps, you can successfully integrate a Django backend with a React frontend. This setup allows you to leverage the strengths of both technologies, creating a powerful and modern web application. Remember to adapt the paths and configurations based on your project's specific structure. Happy coding!
You can find the github repository Here
Deployed on render
Also you can refer to the github repo for the latest update on the integration settings

Top comments (3)

Collapse
 
iteducationcentre1 profile image
iteducationcentre1

To integrate Django and React in a Django project, you need to set up a frontend build pipeline and configure Django to serve the React frontend.

First, create a new Django project using the Django command-line tool. Next, install a package manager like npm or yarn. Use the package manager to create a new React app within the Django project directory.

Configure Django to serve the React frontend by adding the frontend's directory as a static file directory in the project's settings.py file. Build the React app using the package manager in the frontend directory.

In Django's urls.py file, add a catch-all route to redirect undefined routes to the React app's index.html file. Start the Django development server and access the React app in the browser.

Now you have a Django project integrated with React. You can build the frontend using React and communicate with the Django backend through APIs or Django templates.

To learn Reactjs course in Pune visit IT Education Centre

Collapse
 
petrjoe profile image
Akanmu Akinkunmi

You can refer and create an issue on the repository on github via github.com/PetrJoe/React-Django-in...

@iteducationcentre1

Collapse
 
petrjoe profile image
Akanmu Akinkunmi

@iteducationcentre1

Still working in it, i will do that in the update of the project.