There is a lot of moving parts to web development, front end, back end, database, application server, etc. Many people over the years have coined terms such as MERN, MEAN, or even PDRP. These are common software stacks that web developers use for every project. In this tutorial, we'll be exploring the PDRP (PostgreSQL, Django, React, Python) stack to see how we can use React within our Django project. The goal of this tutorial is to create a todo list, with submitting the todos to a back end API using the Django Rest Framework and displaying/consuming the todos with React.
What is React?
What is wrong with HTML5/Bootstrap?
There is a misconception that ReactJS simply will replace HTML5/Bootstrap. This isn't true as there are plenty of use cases where HTML5/Bootstrap is sufficient for your project such as:
Why use Django?
1. Set up your Django project (The REST API)
Lets start by creating a basic Django project. On your PC, create a folder called django-react. Open terminal/CMD on your PC, change the directory to the django-react folder and enter the following:
$ django-admin startproject backend
Now lets create the Django app that'll be our REST API. Inside the same directory that holds manage.py, run the following command in terminal:
$ python manage.py startapp api
At this point, your file structure should look like the following:
Now lets get Django dependancies, Django Rest Framework and django-cors-headers. Inside the terminal/CMD, install those packages by running the following command:
$ pip install django-cors-headers djangorestframework
1A. Adding packages and configure middleware (Editing settings.py)
Open your Django settings file (settings.py). We're going to make a few changes in the settings file to install the rest framework, cors-headers, and our Django app (api). Inside "INSTALLED APPS", enter the following:
#django-react/backend/settings.pyINSTALLED_APPS = ['django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','rest_framework', #Django REST Framework'corsheaders', #CORS Header'api', # our Django app]
Under "MIDDLEWARE", enter the following:
#django-react/backend/settings.pyMIDDLEWARE = ['corsheaders.middleware.CorsMiddleware', # added to solve CORS'django.middleware.common.CommonMiddleware', # added to solve CORS'django.middleware.security.SecurityMiddleware','django.contrib.sessions.middleware.SessionMiddleware','django.middleware.common.CommonMiddleware','django.middleware.csrf.CsrfViewMiddleware','django.contrib.auth.middleware.AuthenticationMiddleware','django.contrib.messages.middleware.MessageMiddleware','django.middleware.clickjacking.XFrameOptionsMiddleware',]
Lastly, we have to let our Django server know that it's safe to use resources from our React application. Lets add the following to the bottom of settings.py:
1B. Connect our app urls to our project urls (Editing backend/urls.py)
As with every Django project, we need to configure the urls.py on the project level. We'll connect the urls.py on our Django app to the root path of our entire Django project. Open urls.py within the backend folder (backend/urls.py) and paste the following:
1C. Setting up our app's url routes (Creating api/urls.py)
We must create our app's urls.py file. Open the api folder and create a new file named "urls.py". Paste the following:
In the code above, we use the rest framework's built-in router method. Using this built-in method provides us a quick way to spin up a API on an endpoint ("todo") on a specific Django url route ("/api") and give us the ability to do GET, POST, PUT, and DELETE requests without configuring these methods manually. Please note that there are many ways to set up url endpoints to the REST API, but we're using this setup so we can have access to the authentication endpoint (using the authentication endpoint is beyond the scope of this tutorial, however I believe that is great start code for people who choose to build upon this tutorial).Later, we're going to setup our project's views.py.
1D. Creating models in api/models.py
Lets create our model. Our model will be a simple comment-like model, taking in a name and detail text fields. Open models.py and paste the following:
1E. Creating api/serializers.py
In the REST framework, serializers are very similar to traditional Django Forms. However, there are some useful extra things happening under the hood that enables all the CRUD actions (GET, POST, PUT, DELETE) for our API. We need to create the serializers.py file in our Django app. Inside the api folder, create a file named serializers.py and paste the following:
1F. Rendering the frontend (Editing api/views.py)
Now this is where things begin to come together. Lets open views.py in our Django app. We're going to setup a function-based view that'll render our React project (we'll create this next) and a class-based view that'll serialize/deserialize the data submitted to Django. Copy and paste the following in views.py:
For now, we're done setting up a Django API. Lets start the Django project for the first time by running migrations, creating a superuser, and starting the server and look at the browsable API. Inside terminal/CMD, run the following commands:
$ python manange.py makemigrations
$ python manage.py migrate
$ python manage.py createsuperuser
$ python manage.py runserverGo to localhost:8000/api. Enter your superuser credentials, and your page may look like this:
Lets make our first submission via the browsable API! Go to localhost:8000/api/todo and scroll down to the bottom, you'll see a section where you can enter a "Name" and "Detail". Enter some text in both of the fields and click the "Post" button. Congratulations, you just made your first POST request to your API. Great, lets create our React project!
2. Installing React
To use React,, we must install NodeJS on our system. Go to https://nodejs.org/en/ and install NodeJS on your system.
After installation is finished, we're going to create our React project within our django-react folder, so both our frontend and backend are together in a single folder. In terminal/CMD, please make sure you're in the root folder for the Django project (.../django-react/) and run the following command:
$ npx create-react-app frontend
$ cd frontend
Now your project folder structure should look similar to this:
3. React code
Open the frontend React project, inside the src folder, open "App.js".
Before we get started, lets install some npm packages (Axios, React-Bootstrap) to improve our React project. We'll use Axios to make requests to our API (I prefer to use Axios as it has better security features compared to window.fetch()), and use React-Bootstrap to add Bootstrap styling to our components. Inside terminal/CMD while inside the frontend folder, run the following commands to install the node packages:
$ npm install axios react-bootstrap
In our React project, we're going to create two new React components (Post and InputForm) and will render both components in the parent component (App.js). In our frontend/src directory, create two new files, Post.js and InputForm.js.
3A. Post.js (Display data from API; GET Request)
All of our React components will be function-based and take advantage of React Hooks. Without going into detail, React Hooks were introduced to help simplify the reusability of stateful objects and and management of complex React components. For more information about React Hooks, take a look at the official documentation.
Now for some code, open Post.js, copy and paste the following:
Lets breakdown this components into four parts: importing packages, defining our state object, making our GET request, and rendering HTML.
Save the file.
3B. InputForm.js (Submit data to API; POST Request)
Open InputForm.js. Copy and paste the following:
Lets breakdown this component, in four parts; the state object "values", rendering the HTML, handle functions, and the POST request.
Great! Save the file, now go to App.js. Here we're going to render both of our components.
3C. App.js (Rendering both components)
Open App.js and paste the following:
All we're doing in App.js is rendering both of InputForm and Post components, and wrapping them in a React-Bootstrap Container. Now save the file. It is time to run both our Django API and React project. Open two terminal/CMD windows, in one window lets run our Django API (make sure you're in the same directory as manage.py:
$ python manage.py runserver
In the second window, run your React project (again, make sure you're in the frontend directory)
$ npm start
Your browser should have two new tabs, lets focus on the React tab (localhost:3000). You should see the submission you made earlier. Go ahead and make a new submission, this time from React.
4. Connecting our React project to Django templates and deploying both together
4A. Create the React build folder
Stop both terminal/CMD windows, and run the following command within the terminal/CMD window you used to run the React project:
$ npm run buildClose the terminal/CMD window, we're finished with setting up our React project.
4B. Edit settings.py (Changing our static files directory to link to our build folder)
Inside of the Django settings file, we have to make two changes, inside the settings.py file, copy and paste the following, replacing the TEMPLATES section:
Now move towards the bottom of the settings file, under STATIC_URL and paste the following:
Great, we just linked our Django static files to our React build folder.
4C. Edit views.py (rendering our React project's index.html)
Lastly, lets render our React project. Open our Django app's views.py folder and add the following:
Save all files. Now go back to termainal/CMD, and start the Django API:
$ python manage.py runserver
Like the content posted on this site? Need help with another web project? Want to give some feedback? Feel free to contact me via email or social media!Know more!