Django and React

This article will discuss the overview of Django and React, their advantages, applications, and most importantly, how to implement react in Django.

What is Django?

Django is a free and open-source web framework, which uses Python as its programming language. It is based on Model View Template (MVT) architecture. Django is known for its rapid development, clean design, and secure websites. A framework is a collection of all the applications needed for web development. It takes care of most of the basics of web development to not have to write code from scratch every time. It was first created in 2003 by two web programmers called Adrian Holovaty and Simon Willison. It was publicly released in 2005 under the BSD license. The final version of Django was released in 2008, and a newly formed organization, Django Software Foundation, was announced to maintain Django in the future. 

Pros and Cons

Pros of Django

  • It is swift, there are already very helpful frameworks, and it can reduce the development time.
  • It provides very secure websites which are protected from different attacks such as SQL injections etc.
  • Django has an outstanding community and documentation that can help developers.
  • One of the significant advantages of Django is that it is immensely scalable and can handle the traffic of more than 350 million users. It also provides very cheap hosting.

Cons of Django

  • In Django, if we have to specify URLs, then we have to use Regex for that. It can easily become very complex and complicated.
  • Django has got a substantial structure and too many functionalities for a minor project. It is an intensive coding framework and requires a lot of processing time. So if the project is not that big, think about it before doing all the hard work.
  • Django has a major disadvantage of processing only one request at a time which makes it hard for developers to send API requests.
  • Django has a monolithic framework. All the modules in Django have to be compatible backward, which slows down the evolution.

What is React?

ReactJS is used to build UI components. It is a JavaScript library. React is a component-based library, and just like Django, it is also.

-source. React is not a framework but just a library. React can be considered as V, i.e., View for MVC (Model-View-Control) architecture. React gives better performance by changing the Virtual DOM instead of the actual DOM. Reacts follow the one-way data flow. React is heavily used to create large apps because of its components structure.

Pros and Features

  • Beginner-friendly:ReactJS is considered to be very beginner-friendly and easy to use. React uses the JSX syntax, which is very similar to JS and HTML. Since React is an open-source library, constant improvement and modifications are done to it regularly.
  • Virtual DOM: The virtual DOM is more efficient than normal DOM, and also it is faster. The problem with the real DOM is that when even a small update is done in a UI component, the whole DOM tree is rewritten. This process consumes time and is not efficient. On the other hand, the virtual DOM just updates the component, which is updated by the user, unlike real DOM, which updates the whole tree. Modern websites have a really large DOM tree, so using the virtual DOM is much more efficient.
  • Reusable Components: React uses the component structure to build applications. These components can be re-used to build multiple UI and pages for the application. This reusability reduces the production time for developing the application.
  • One-way data flow: Unlike other JavaScript applications, React uses the one-directional data flow. In the multi-directional data flow, when a child component is changed, it also changes its parent components which are not ideal and can be hard to debug. React resolves this problem by providing a one-way data flow so the parent component cannot change after changing the child component.

Cons:

  • React is the View part of the MVC architecture. So to use React, we still have to find the Model and Controller for the View.
  • Documentation is one of the cons of React. React is so fast and quickly developing that its documentation is lagging. The documentation is not friendly for beginners and not extensive.
  • React JSX is not considered to be good by some of the React community members. JSX has a syntax that is a mixture of HTML and JavaScript. It also has some advantages to it.

Implementing React with Django

We will want to connect a frontend to the backend to do CURD or similar operations or fetch the database.

First, we will set up our application inside a virtual environment.

virtualenvnewenv
cdnewev
source bin/activate
django-admin.pystartprojectmyproject
cdmyproject
Django-adminstartapp core

Now let's define our model in our models.py file. We will store the name and detail of the student.

Models.py

fromDjango.db import models


# Create your models here.




classStudent(models.Model):
name = models.CharField(max_length=30)
detail = models.CharField(max_length=500)

Now connect the model to the database through the migrations. To connect to the database, run the below command in the terminal:

python manage.py makemigrations
python manage.py migrate

The later command applies the change to the database.

The next step is to define the serializers. Serialization is the act of changing the object into another data format. They are used to render the data in Python easily.

fromrest_framework import serializers
from .models import *


classSerializer(serializers.ModelSerializer):
class Meta:
model = Student
fields = ['name', 'detail']

Now let us create the views.py for the GET, PUT, POST, and DELETE operations. Copy the following code in core/views.py:

fromDjango.shortcuts import render
fromrest_framework.views import APIView
from .models import *
fromrest_framework.response import Response
from .serializer import *
# Create your views here.


classStudent_View(APIView):


ser_class = Serializer


def get(self, request):
detail = [ {"name": detail.name,"detail": detail.detail} 
for detail in Students.objects.all()]
return Response(detail)


def post(self, request):


serializer = Serializer(data=request.data)
ifserializer.is_valid(raise_exception=True):
serializer.save()
return  Response(serializer.data)

Now use the following code in urls.py:

fromDjango.contrib import admin
fromDjango.urls import path
from students import views
fromDjango.conf.urls import url


urlpatterns = [
path('admin/', admin.site.urls),
path(‘std/’,Student_View.as_view()),
]

Now just make some changes in settings.py.

Add the app coreto the INSTALLED_APPS.

Install the cors middleware and add it to the MIDDLEWARE section.

Now just run the server by using the below command:

After successfully running the server, go to the localhost:8000/std, and you will see something like this:

Django and React

Building React App

Let us set up the react project by these commands:

Npx create-react-app studentslist
Cd students list

Axios is used to connect the frontend and backend.

After creating the project you will see a App.js file in your main directory, copy the following code in app.js :

import React from 'react';
class App extends React.Component {
	render() {
		return(
			<div>
				<h1>Student List</h1>				
				/div>);
	}


}
export default App;

Now we have to fetch the data every time we render the react app. We do this by using Axios.

import React from 'react';
importaxios from 'axios';


class App extends React.Component {


	state = {
		details : [],
	}


	componentDidMount() {


		vardata ;


		axios.get('http://localhost:8000/std/')
		.then(res => {
			data = res.data;
			this.setState({
				details : data	
			});
		})
		.catch(err => {})
	}


render() {
	return(
	<div>
			{this.state.details.map((detail, id) => (
			<div key={id}>
			<div>													<h1>{detail.detail} </h1>
				<div class = “text”>
                        				---
                        				{detail.name}
                     			 
</div>
					
			</div>
			</div>
			)
		}
	</div>
	);
}
}
export default App;

Now add some data to the student model and run the react server by running this command in command prompt and browse to the localhost:300 in your browser.

Npm start
Django and React

This is just the beginning, and you can expand this application by adding many features to it, like a form for the user to add some new students to the model.


Related Topics

Django REST Framework

Django REST Framework (DRF)is an open-source, powerful, and flexible toolkit used to build RESTful web APIs. It is built upon the Django framework. DRF increases the development speed. Django and...

4 minutes read.

Django Stack

Django is a popular Python web application framework that adheres to the "batteries-included" tenet. Batteries-guiding included idea is that common functionality for creating web applications should be provided with the...

5 minutes read.

Django Model Fields

In Django, if we want to store the information about anything, we use Models. It contains various fields about the data. Generally, each model represents a database where all the...

4 minutes read.

Django Pagination

Django is an open-source free to use python based web framework. Django provides many inbuilt tools for web developers to provide rapid web development. One of these tools is pagination....

4 minutes read.

Django Logging

Every application developed has some bugs and errors. It is the responsibility of the developers to maintain the application by making it bug-free and error-free. To debug the application code...

5 minutes read.

Django vs Laravel

Django Overview Django is a Python Programming Open Source framework for web development. It was released in 2008 and was developed by two web developers named Adrian Holovaty and Simon Willison....

4 minutes read.

Django Messages

Django Framework Django is a framework that can make web applications more accessible and faster. Django is an open-source collection of python libraries, and Django can be used for both the...

6 minutes read.

Django MVT

 MVT(Model View Template) MVT means Model View Template is a software design pattern The View is used to implement the business logic and to communicate with a model for data transmission and to...

2 minutes read.

Django Channels

Channels is a project that uses Django and adds some functionalities beyond the traditional HTTP by using WSGI and ASGI.  We can use both synchronous and asynchronous requests with ASGI...

5 minutes read.

Django Image Upload

Django is a python based web framework that uses Model View Template as its architecture. Django provides really quick web development with its functionalities. While we are building a website,...

3 minutes read.

Django Project

Django Project Let's start to use it. Each web app you want to build in Django is called a project; and a project is a collection of apps. A software is a series of...

3 minutes read.

Django ORM

Django is a Python web framework that enables easy and quick web development. Django has a handy and powerful feature called Django Object Relational Mapper, also known as Django ORM,...

3 minutes read.

Django Filters

Django is a high-level python based web framework. Django is mostly used as a backend engine for websites. Nowadays, every website communicates to a database to fetch all the information...

3 minutes read.

Django Authentication

Django is an open-source free to use web framework which is based on Python. Django uses Model-View-Template as its architecture. The final version of Django was released in 2008. Django...

4 minutes read.

Django Frontend

Django Django is a framework that can make web applications more accessible and faster. Django is an open-source collection of python libraries, and Django can be used for both the front...

3 minutes read.

Django Create App

Django is a Python-based web framework that is based on the Model View Template architecture. In this post, we will go through the installation and setup for our first Django...

4 minutes read.

How to Uninstall Django from cmd

Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Django Environment Setup

Django is a free and open-source web framework, which uses Python as its programming language. It is based on Model View Template (MVT) architecture. A framework is a collection of...

4 minutes read.

How to connect Django with Mysql

Any web application contains some data that comes from the input of the end-users. Thus, the database is required to handle those data. Several databases could be used to connect...

3 minutes read.

What is Django?

What is Django? Django is a free and open-source web application framework, written in Python. A web framework is a set of components that help you develop an easier and faster website. When we...

3 minutes read.