Open In App

How to connect Django with Reactjs ?

React is a JavaScript library created by Facebook. It is a tool for building a UI (User Interface) component. It is widely used for making SPA(Single Page Application) and it has a large developer community.

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:

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.



The above advantages will eventually result in only a single task left i.e. connection.  

Prerequisites:

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.

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
cd env
source bin/activate

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
cd quotes
django-admin startapp core

Step 5:




from django.db import models
  
# Create your models here.
  
  
class React(models.Model):
    name = models.CharField(max_length=30)
    detail = models.CharField(max_length=500)




from rest_framework import serializers
from . models import *
  
class ReactSerializer(serializers.ModelSerializer):
    class Meta:
        model = React
        fields = ['name', 'detail']




from django.shortcuts import render
from rest_framework.views import APIView
from . models import *
from rest_framework.response import Response
from . serializer import *
# Create your views here.
  
class ReactView(APIView):
    
    serializer_class = ReactSerializer
  
    def get(self, request):
        detail = [ {"name": detail.name,"detail": detail.detail} 
        for detail in React.objects.all()]
        return Response(detail)
  
    def post(self, request):
  
        serializer = ReactSerializer(data=request.data)
        if serializer.is_valid(raise_exception=True):
            serializer.save()
            return  Response(serializer.data)

Step 6:




from django.contrib import admin
from django.urls import path, include
from django.conf.urls import url
from core.views import *
  
urlpatterns = [
    path('admin/', admin.site.urls),
    path('wel/', ReactView.as_view(), name="something"),
]

Step 7: There are few changes in settings.py file which are listed below 

  1. Add rest_framework , core, corsheaders  to INSTALLED APPS
  2. Add corsheaders.middleware.CorsMiddleware to MIDDLEWARE list.
  3. Create  a dictionary assigned to REST_FRAMEWORK variable in which insert ‘DEFAULT_PERMISSION_CLASSES’: [   ‘rest_framework.permissions.AllowAny’ ]
  4. 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.

python manage.py makemigrations 
python manage.py migrate  
python manage.py createsuperuser --email admin@example.com --username admin 
python manage.py runserver

OR

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
cd 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.

Inside our-quote/src/App.js:




import React from 'react'
class App extends React.Component { 
    render() { 
        return(
            <div>
                <div>
                    <div>
                        <h1>Quote is going to be written here</h1>
                        <footer>--- by
                          <cite title="Source Title"
                              written by meeeee 
                          </cite>
                        </footer>
                    </div>
                </div>
            </div>); 
    
export default App;

Output: After running npm start development server of React will start and by default can view at localhost:3000 

App.js: Now we have to fetch data from the server by using Axios. The componentDidMount method is called when the component is rendered. This is the right time to request a server for the data. We have used Axios in this method to store the data in a state obtained from the server and later on rendered by the help of a map in JavaScript. 




import React from 'react';
import axios from 'axios';
  
class App extends React.Component {
  
    state = {
        details : [],
    }
  
    componentDidMount() {
  
        let data ;
  
        axios.get('http://localhost:8000/wel/')
        .then(res => {
            data = res.data;
            this.setState({
                details : data    
            });
        })
        .catch(err => {})
    }
  
  render() {
    return(
      <div>
            {this.state.details.map((detail, id) =>  (
            <div key={id}>
            <div >
                  <div >
                        <h1>{detail.detail} </h1>
                        <footer >--- by
                        <cite title="Source Title">
                        {detail.name}</cite>
                        </footer>
                  </div>
            </div>
            </div>
            )
        )}
      </div>
      );
  }
}
  
export default App;

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.




import React from "react";
import axios from "axios";
  
class App extends React.Component {
    state = {
        details: [],
        user: "",
        quote: "",
    };
  
    componentDidMount() {
        let data;
  
        axios
            .get("http://localhost:8000/wel/")
            .then((res) => {
                data = res.data;
                this.setState({
                    details: data,
                });
            })
            .catch((err) => {});
    }
  
    renderSwitch = (param) => {
        switch (param + 1) {
            case 1:
                return "primary ";
            case 2:
                return "secondary";
            case 3:
                return "success";
            case 4:
                return "danger";
            case 5:
                return "warning";
            case 6:
                return "info";
            default:
                return "yellow";
        }
    };
  
    handleInput = (e) => {
        this.setState({
            [e.target.name]: e.target.value,
        });
    };
  
    handleSubmit = (e) => {
        e.preventDefault();
  
        axios
            .post("http://localhost:8000/wel/", {
                name: this.state.user,
                detail: this.state.quote,
            })
            .then((res) => {
                this.setState({
                    user: "",
                    quote: "",
                });
            })
            .catch((err) => {});
    };
  
    render() {
        return (
            <div className="container jumbotron ">
                <form onSubmit={this.handleSubmit}>
                    <div className="input-group mb-3">
                        <div className="input-group-prepend">
                            <span className="input-group-text"
                                  id="basic-addon1">
                                {" "}
                                Author{" "}
                            </span>
                        </div>
                        <input type="text" className="form-control" 
                               placeholder="Name of the Poet/Author"
                               aria-label="Username"
                               aria-describedby="basic-addon1"
                               value={this.state.user} name="user"
                               onChange={this.handleInput} />
                    </div>
  
                    <div className="input-group mb-3">
                        <div className="input-group-prepend">
                            <span className="input-group-text">
                               Your Quote 
                            </span>
                        </div>
                        <textarea className="form-control " 
                                  aria-label="With textarea"
                                  placeholder="Tell us what you think of ....." 
                                  value={this.state.quote} name="quote" 
                                  onChange={this.handleInput}>
                        </textarea>
                    </div>
  
                    <button type="submit" className="btn btn-primary mb-5">
                        Submit
                    </button>
                </form>
  
                <hr
                    style={{
                        color: "#000000",
                        backgroundColor: "#000000",
                        height: 0.5,
                        borderColor: "#000000",
                    }}
                />
  
                {this.state.details.map((detail, id) => (
                    <div key={id}>
                        <div className="card shadow-lg">
                            <div className={"bg-" + this.renderSwitch(id % 6) + 
                                          " card-header"}>Quote {id + 1}</div>
                            <div className="card-body">
                                <blockquote className={"text-" + this.renderSwitch(id % 6) + 
                                                   " blockquote mb-0"}>
                                    <h1> {detail.detail} </h1>
                                    <footer className="blockquote-footer">
                                        {" "}
                                        <cite title="Source Title">{detail.name}</cite>
                                    </footer>
                                </blockquote>
                            </div>
                        </div>
                        <span className="border border-primary "></span>
                    </div>
                ))}
            </div>
        );
    }
}
export default App;

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.


Article Tags :