Integrating Django and React in a Django Project
Tags: javascript, programming, django, react
Published: 2023-12-08 01:42:26

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()

```


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')
```


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)
```

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](https://github.com/PetrJoe/React-Django-integration)
[Deployed on render ](https://reactdjango.onrender.com)
Also you can refer to the github repo for the latest update on the integration settings