Django Unleashed

Unleashing the Full Potential of Web Development

Serving a React App in Django: A Step-by-Step Guide

--

Summary

Discover how to mix React with Django in easy steps! Follow along to put your React app right into Django, making front-end and back-end work together smoothly.

Let’s Begin

Alright, first, we have to make a Django project.

django-admin startproject react_django_example

Next, we gotta create a Django app inside the project we made.

cd react_django_example
python manage.py startapp react

Include the react Django app you made in the INSTALLED_APPS section of your settings.py.

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
"react",
]

Now, you gotta put this code into your react/views.py file.

import posixpath
from pathlib import Path

from django.utils._os import safe_join
from django.views.static import serve as static_serve

def serve_react(request, path, document_root=None):
path = posixpath.normpath(path).lstrip("/")
fullpath = Path(safe_join(document_root, path))
if fullpath.is_file():
return static_serve(request, path, document_root)
else:
return static_serve(request, "index.html", document_root)

Also, put this code into your react_django_example/urls.py file.

from django.contrib import admin
from django.urls import path, re_path
from django.conf import settings

from react.views import serve_react

urlpatterns = [
path('admin/', admin.site.urls),
re_path(r"^(?P<path>.*)$", serve_react, {"document_root": settings.REACT_APP_BUILD_PATH}),
]

Now, we’re gonna make a React application.

npx create-react-app react_app_example

After that, we need to build our React application.

cd react_app_example
npm run build

Now, you gotta put the address of the React app’s build folder into the settings.py file.

REACT_APP_BUILD_PATH = "react_app_example/build"

Sometimes, it’s better to change the STATIC_URL in your Django project so it doesn’t mess with the static folder in your React app.

STATIC_URL = 'django_static/'

Now, just run your Django project and check out the result.

python manage.py migrate
python manage.py runserver

Now, if you visit http://127.0.0.1:8000/, you should see the result.

And that’s it. You can serve your React app using the Django project and enjoy it.

--

--

Django Unleashed
Django Unleashed

Published in Django Unleashed

Unleashing the Full Potential of Web Development

Rashad Ansari
Rashad Ansari

Written by Rashad Ansari

Curious and continuously learning software engineer, driven by crafting innovative solutions with passion. Let’s collaborate to shape a better future!

No responses yet