As a Django backend developer you might need to collaborate with a frontend dev who uses react or you might be a full stack developer interested in building the front end of your applications with react( which I believe we all love by the way 😌). Then you need to learn how to interface a react frontend application to your Django backend. This tutorial will guide you through the easy steps. We are going to set up the Django backend first then we'll set up our react frontend and finally connect them.
You can also access the Github repo for the completed tutorial here
Setting up the Django backend.
I’ll assume that you already have python installed on your machine. If you don't, you can download and set it up via this link. Please ensure you download the latest version of python. (Python 3.97)
Open the Command Line on Windows, Terminal on Mac, and Linux and navigate to the directory where you want to store the project and create a new directory
mkdir React-Django
Move into the new directory
cd React-Django
Create a Virtual environment.
It is recommended to always create a virtual environment before you start your project. This helps you to separate the packages you use in this application from other applications; any change you make here won't affect the same package in another application on your system. To create a virtual environment on your system; run this command:
For mac/unix users: python3 -m venv env
For windows users: py -m venv env
After creating the environment, activate it by running :
For mac/unix users: source env/bin/activate
For windows users: .\env\Scripts\activate
You can deactivate it by simply running the command below, but you don't have to deactivate it yet.
deactivate
Installing Django
Now let us proceed to install Django,
pip install django
Create a new Django project and name it “project1”
django-admin startproject project1
Move into the project directory
cd project1
Migrate your “changes” with this command
python manage.py migrate
Then you can start your server to ensure that everything is working properly
python manage.py runserver
Copy this URL: http://127.0.0.1:8000 and open it in any browser of your choice. You should be able to see something similar to this 👇
Setting up the react frontend.
Next, we need to create the frontend react application in the current directory project1
that contains the manage.py
file:
npx create-react-app frontend
Move into the frontend directory
cd frontend
and then start the frontend application by running
npm start
You should see the default react application page in your browser now; if you cannot see it open this link in your browser.
http://localhost:3000
We won't be making any other change to the installed react application so we are done here but we need to build the package which the backend will make use of by running:
npm run build
and then we also need to remove /build
from the gitignore file since the backend would need to make use of the templates
and staticfiles
in the build folder.
Now let's head to the backend setup and connect it to the react application we just created.
Interfacing the front end application to the Django backend.
Move back into the root folder
cd ..
Next, we'll be making some changes to the settings.py file in the backend project file so that the Django backend can recognize the react application we created as the default frontend directory. Open up the settings.py file and make the following changes.
Import 'os' at the top of the file
import os
then configure the template directory by pointing it towards the build folder in our frontend react directory.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'frontend', 'build')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
We need to configure the static files directory as well; add this line to the bottom of the page below the STATIC_URL line.
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'frontend', 'build', 'static')]
We are done with the setup. So let us go ahead and create a simple view that will display our default react page.
python manage.py startapp core
Don't forget to add the new app "core" to the "INSTALLED APPS" section in your settings.py file.
Open the views.py file and create a simple function-based view that just renders our page.
def front(request):
context = { }
return render(request, "index.html", context)
Then we map the created view to a URL in our urls.py
file in the project1
folder. We import the "front" view function from the core app and we map it to the default URL " ".
from django.contrib import admin
from django.urls import path
from core.views import front
urlpatterns = [
path('admin/', admin.site.urls),
path("", front, name="front"),
]
The work is done. Now run
python manage.py runserver
Reload the page in your browser and you should now see the react page we saw earlier.
Notice that the URL is now http://127.0.0.1:8000.
We have successfully connected our Django backend to a react frontend. You will need the Django REST framework to create the APIs the react frontend application will make use of to get backend data.
Note
If you want to create your frontend directory outside the Django directory. You'll need to get the path that points to the overall base directory that will hold both your backend
and frontend
directories.
Add this line below the BASEDIR
variable at the top of the settings.py file.
REAL_BASE_DIR = Path(__file__).resolve().parent.parent.parent
Next, the new variable REAL_BASE_DIR
will be used in the Templates
and Staticfiles
sections.
Templates:
'DIRS': [os.path.join(REAL_BASE_DIR, 'frontend', 'build')],
STATICFILES_DIRS = [os.path.join(REAL_BASE_DIR, 'frontend', 'build', 'static')]
This will ensure that Django searches for templates and static files in your frontend
folder which is outside the Django directory.
Congratulations! Now you can get started on that great project idea of yours by using any of the two methods above!! Cheers!!
If you have any questions, feel free to drop them as a comment or send me a message on Linkedin or Twitter and I'll ensure I respond as quickly as I can. Ciao 👋
Top comments (24)
Great article but I'd like to add two things:
If you're using Git, React includes /build in its gitignore so that builds won't go into the repository but since you're serving your React app from Django, the build also needs to be in the project as if it were the standard templates and static files.
That's why I usually rename my build folder to something like react_build and use this name in my Django settings file.
Another thing, in a React SPA, React itself should take care of the routes and display the proper components, probably with react-router. In your example, what happens if I create a page in my React app in /dashboard for instance and go to 127.0.0.1:8000/dashboard ?
Django will throw a 404 because there's no /dashboard in the urls.py but that should not have been handled by Django but by React.
For that problem, what I'm doing is using a regex in urls.py that captures any path that should not be handled by Django and redirect them to the React app.
So for instance, my base urls.py will contain /admin, /api, /static and some other specific files and after all those, the regex that sends the React app back to any URL path so that React itself does the routing and display the appropriate components or a 404 page. My current regex is:
re_path('(?!.*(static))', TemplateView.as_view(template_name="index.html", content_type="text/html"))
Need to import re_path from django.urls and import TemplateView from django.views.generic or replace it with a view like in your example.
I hope that makes sense.
Yes it does. Thanks for reading. I'll look into the points you raised.
Informative! Keep it up!
Thank you
thanks for the most significant contribution
Thanks for reading
Great article!
Can you also do a simplistic API tutorial to add to this?
Hello Shingirai. Thanks for reading. I'll look for time to do that!! Fingers crossed
hey, this is exactly what i was looking for thanks!!
one doubt however, how would you deploy it?
Say we have a single repo for both
Application
|Django_BackendCode
|ReactFrontendCode
How would you deploy this?
deploy the backend separately (say at api.backend.com), and use
api.backend.com
to fetch data using axios?Can I use pycharm to do all of this because it's easy to do the setup in pycharm instead of visual studio. What framework did you use? And another question do we need a lot of knowledge about python to dig deep into django.
Yes you can use any editor of your choice. You dont need to be a python guru to use django, but you need to understand the fundamentals of python strongly.
Can I connect Django with ReactJS with the folder structure like following picture?
dev-to-uploads.s3.amazonaws.com/up...
Hello xuwenjing. Yes you can use the folder structure in your attached picture. However, note that you will need to make few changes to your
settings.py
file.1) You have to use a 'path' that would point to the
build
directory in yourfrontend
directory. You can find the code for that here: dev-to-uploads.s3.amazonaws.com/up...2) Next, under the templates and static files sections., you have to change the variable
BASE_DIR
to the new variableREAL_BASE_DIR
created in 1 above.Templates: 'DIRS': [os.path.join(REAL_BASE_DIR, 'frontend', 'build')]
Staticfiles: STATICFILES_DIRS = [os.path.join(REAL_BASE_DIR, 'frontend', 'build', 'static')]
This ensures that Django searches for templates and static files in your
frontend
folder which is outside the Django directoryThanks!
I followed the steps, but I only got a blank page: dev-to-uploads.s3.amazonaws.com/up...
The message when running : dev-to-uploads.s3.amazonaws.com/up...
Could you please have a look? Thanks for your help~
Hello xuwenjing,
The message displayed when running is okay. It shows that there is no issue with your code.
Regarding the blank page. Did you remember to run
npm run build
in your frontend directory?Can i see your frontend directory?
Can you update this with examples that show full paths of the Django project and React project? For example.
C:\Backend\React Django\env\project1
C:\Frontend\react-project\
Otherwise as it is, it is a bit confusing -
'DIRS': [os.path.join(BASE_DIR, 'frontend', 'build')], - BASE_DIR IS IN Django and back end repo so why add the front end which is supposed to be in its own front end repo
React-Django\env\project1\ - Django project and apps
But what directory is this in relation to the react project directory “front end” noting that you will git init this to the Django repo, my guess is that the react project front end folder will be in a different folder, correct? But based on your template directory configuration, this is confusing as it shows that the template directory is in the Django project folder?
React front end folder and path ??
What directory is this in relation to the django project directory? is this frontend folder in the django project??
Hello Bernard. Here is a screenshot of the folder structure for the tutorial: dev-to-uploads.s3.amazonaws.com/up...
The react frontend application folder replaces the default templates folder from which Django is meant to locate and load templates which would normally be specified in this format
'DIRS': [BASE_DIR/ 'templates']
.However, since we want the Django backend to make use of a react frontend while using a single server:
http://127.0.0.1:8000
, we need to point Django to the folder where it will get the frontend files which in the tutorial above is thebuild
folder in the frontend directory. Hence the necessity for theSTATICFILES_DIRS = [os.path.join(BASE_DIR, 'frontend', 'build', 'static')]
line.Great! Thanks!
Great Tutorial! I really want to finish it, but unfortunetly i'm getting errors when trying to run python manage.py startapp core(Refer to the image for error). any assitance would be apprecaited 🙏🏻 I did make sure 'core' was added to my INSTALLED _APP section and removed /build from the .gitignore.
Thank you!
Here is the link to the repository where the project lives
github.com/Moodybleu/project1