How to connect Django with Reactjs ?
Django is a Python-based web framework that encourages rapid development and clean, pragmatic design. Due to its ready-made and stack full of wonderful features, from authentication to session management, all these make it ridiculously fast.
Reason to choose React with Django:
- Both React and Django are the most popular library and frameworks and are splendid in their respective domains.
- React’s wonderful SPA optimization and Django’s powerful features make it even better.
- They have large community support and provide immediate assistance.
Advantages of connecting React with Django: As both the parts will be handled separately i.e. React and Django. Here is the list of advantages of using them separately.
- Cleaner and Clear interface between front-end and back-end logic and functions.
- Easy to deploy either the front-end part or the back-end part without redeploying the other.
- Smoothing User Experience, with less loading times and less perceived transitions-data is fetched in the background and only a part of the whole component will be reloaded.
- If there are separate teams working in front-end and back-end respectively they need not worry about another part as both can work independently.
- Can create scalable and multiple client (web, mobile) apps. All the clients will have to consume the same API provided by the back-end side.
The above advantages will eventually result in only a single task left i.e. connection.
- A development machine with any OS (Linux/Windows/Mac).
- Python 3 installed.
- Node.js installed (version 12+).
- npm installed (version 6+).
- Basic understanding of both the frameworks (Django and React).
Connect front-end with back-end: This usually happens because we start learning either front-end part (HTML, CSS, Bootstrap, or React, Angular, or Vue if using the framework) or back-end part (Node.js, Django, etc. or any other framework). Anyways that’s the way of learning.
Let’s understand the basic workflow of the connection. These 2 key points are building blocks of Web Technologies.
- In the back-end, we will create API using Django- rest (having methods like GET, POST).
- In front-end, we will consume the API made in Django by hitting it using React.
About the Project: This project is a simple application in which you can write a quote and the name of the author. Basically based on CRUD(Create Read Update and Delete) operation.
Setting Up the back-end: Create a project folder for Django by creating a virtual environment. You must have installed virtualenv package.
Step 1: If not installed install it by typing a command on terminal.
python3 -m pip install --user virtualenv
Step 2: Create a virtual environment.
python3 -m venv env
Step 3: Install below packages by using pip
pip install django
pip install djangorestframework
python -m pip install django-cors-headers
Step 4: Create a project name of your choice.
django-admin startproject quotes
django-admin startapp core
- models.py: Now let’s create a database model for our project. As the project is a very simple and model is sufficient to illustrate. Here is models.py file of core app. Name and detail are two fields that are used to store the name of the author and the quote submitted by the author respectively.
- serializer.py: Create serializer.py inside the core folder. Here is the serializer for model React. Serializers are basically used to convert complex data to native Python datatypes that can then be easily rendered into JSON(Which we are going to use in React i.e. Client side).
- views.py: Here is views.py in which we can create our method like GET, PUT, POST, DELETE. I have created GET and POST using class-based views of Django. In GET method we are returning data from the model by calling React.objects.all() and then using list comprehension to convert the author and their quotes in python’s dictionary. In the POST method, we are simply saving the data bypassing the data to ReactSerializer(). It’s time to define the endpoint of the API. The end-point of an API is the URL where our client will hit to consume data from the server. It is generally the place where our resources (database and other programmed functions) live.
- urls.py: Here is the main urls.py from the project quote. The localhost:8000/wel/ is the end-point of our ReactView.
Step 7: There are few changes in settings.py file which are listed below
- Add rest_framework , core, corsheaders to INSTALLED APPS
- Add corsheaders.middleware.CorsMiddleware to MIDDLEWARE list.
- Create a dictionary assigned to REST_FRAMEWORK variable in which insert ‘DEFAULT_PERMISSION_CLASSES’: [ ‘rest_framework.permissions.AllowAny’ ]
- Assign variable CORS_ORIGIN_ALLOW_ALL = True
You might be thinking about the corsheaders package. Actually, the cors headers package is used to tell the browser that web application running at one origin, access to selected resources from a different origin.
Now let’s get back to the final part of our back-end. Run the following commands on the terminal.
- This command is used to detect changes made in the database.
python manage.py makemigrations
- This command applies those changes to the database.
python manage.py migrate
- For creating a superuser who will be the admin of the whole app.
python manage.py createsuperuser --email email@example.com --username admin
- This command will run the server and the server should always be in running state.
python manage.py runserver
Open the web browser of your choice (Chrome recommended) and search for localhost:8000/wel/
Setting Up the front-end: There is no boundation to make the front-end folder in the same directory where the back-end folder lives. Also, there is no need of making a virtual environment for React. Use the following commands to get ready for React Application. Using Bootstrap for styling and better look and feel, jQuery is for the dependencies with bootstrap.
npx create-react-app our-quote
npm install bootstrap jquery axios
Axios is the main tool for connecting back-end with front-end. All the requests will be sent to the server (back-end) with the help of Axios.
Output: After running npm start development server of React will start and by default can view at localhost:3000
Output: As there is no data to display so fill some data in the database from the server-side.
App.js: Now the only part left with this project is to create a form so that the user can fill the data from Client-side which is the correct way to do so. Here is the form submitting a response from Client-side along with bootstrap.
Output: The form will call handleSubmit which in return is using the POST method and submitting the response at end-point http://localhost:8000/wel/. The renderSwitch() is used for passing the index of the array which in return the color of bootstrap className.
Please Login to comment...