How to connect Django to ReactJs
Tags: javascript, webdev, react, django
Published: 2021-11-09 09:46:44


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](https://github.com/Faruqt/React-Django)

#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](https://www.python.org/downloads/). 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 
```javascript
mkdir React-Django
```
Move into the new directory
```javascript
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:
```javascript
For mac/unix users: python3 -m venv env
For windows users: py -m venv env
```

After creating the environment, activate it by running :

```javascript
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.
```javascript
deactivate
```

###Installing Django
Now let us proceed to install Django,
```javascript
pip install django
```
Create a new Django project and name it “project1”
```javascript
django-admin startproject project1
```
Move into the project directory
```javascript
cd project1
```
Migrate your “changes” with this command
```javascript
python manage.py migrate
```
Then you can start your server to ensure that everything is working properly 
```javascript
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 👇
![Django default page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i70ngak6274xhrpkvhcm.png)

#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:
```javascript
npx create-react-app frontend
```
Move into the frontend directory
```javascript
cd frontend
```
and then start the frontend application by running
```javascript
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.
```javascript
http://localhost:3000
```
![react default](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mmpra1xpsht2bx1o7ls2.png)

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:
```javascript
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
```javascript
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
```javascript
import os
```
then configure the template directory by pointing it towards the build folder in our frontend react directory.

```javascript
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.
```javascript
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.
```javascript
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.
```javascript
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 " ".
```javascript
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
```javascript
python manage.py runserver 
```
Reload the page in your browser and you should now see the react page we saw earlier. 
![React+Django](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2liziwxlgusvbrbn0dvh.png)

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.
```javascript
REAL_BASE_DIR = Path(__file__).resolve().parent.parent.parent
```
![folder structure for django+react](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hi3uge1k5xia1fq07o2h.png)

Next, the new variable `REAL_BASE_DIR` will be used in the `Templates` and `Staticfiles` sections.

Templates:
```javascript
'DIRS': [os.path.join(REAL_BASE_DIR, 'frontend', 'build')],
```
![Django Templates path](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3f7r2yuxsowhbsoylpck.png)
Staticfiles:
```javascript
STATICFILES_DIRS = [os.path.join(REAL_BASE_DIR, 'frontend', 'build', 'static')]
```

![Django React Static files path](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lo9c2uvrmbiefep0p5k5.png)
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!!

>Django + React
![Thanos with infinity gauntlet](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ll11n5ixsn6eej8qzxxt.gif)

If you have any questions, feel free to drop them as a comment or send me a message on [Linkedin](https://www.linkedin.com/in/faruq-abdulsalam) or [Twitter](https://twitter.com/Ace_II) and I'll ensure I respond as quickly as I can. Ciao 👋