How to connect Django with Reactjs ? - GeeksforGeeks
Technology

How to connect Django with Reactjs ? – GeeksforGeeks

How to connect Django with Reactjs ? – GeeksforGeeks

How to connect react to django

react is a javascript library created by facebook. is a tool to build a ui component (ube iinterface). is widely used for making spa(ssingle page aapplications) and has a large developer community.

djangois a python-based web framework that encourages rapid development and clean, pragmatic design. because it’s out of the box and packed with wonderful features, from authentication to session management, it all makes it ridiculously fast.

reason for choosing react with django:

  • both react and django are the most popular libraries and frameworks and are splendid in their respective domains.
  • the wonderful spa optimization of react and django. strong> powerful features make it even better.
  • have great community support and provide immediate assistance.

advantages of connecting react with django: since both parts will be handled separately ie react and django. here is the list of advantages of using them separately.

  • cleaner and clearer interface between front-end and back-end logic and functions.
  • easy to implement either the front-end part or the back-end part. end without re-implementing the other.
  • smoother user experience, with less load times and fewer perceived transitions: data is fetched in the background and only one reload will take place. part of the whole component.
  • if there are separate teams working on front-end and back-end respectively, they don’t need to worry about another part, as both can work independently.
  • they can create scalable, multi-client (web, mobile) applications. all clients will need to consume the same api provided by the back-end.

The above advantages will eventually result in only one task remaining, ie connection.

Prerequisites:

  • a development machine with any operating system (linux/windows/mac).
  • python 3 installed.
  • node.js installed (version 12+).
  • npm installed (version 6+).
  • basic understanding of both frameworks (django and react).

connect the front-end with the back-end: this usually happens because we start learning any of the front-end parts (html, css , bootstrap, or react, angular, or vue if you use the framework) or back-end part ( node.js, django, etc. or any other framework). anyway, that’s the way to learn.

let’s understand the basic workflow of the connection. these 2 key points are basic components of web technologies.

  • on the back-end, we’ll create an api using django-rest (with methods like get, post).
  • on the front-end, we’ll consume the api created in django by hitting it using react.

About the project: This project is a simple application where you can write a quote and the name of the author. basically based on crud(create rlead update and delete) operation.

Screenshotfrom20200731180049.png

set up the backend: create a project folder for django by creating a virtual environment. you must have the virtualenv package installed.

Step 1: If it is not installed, install it by typing a command in the terminal.

step 2: create a virtual environment.

Step 3: Install the following packages using pip

step 4: create a project name of your choice.

Screenshotfrom20200726032659-660x271.png

step 5:

  • models.py: Now we are going to create a database model for our project. since the project is very simple and the model is enough to illustrate. here is the models.py file for the main application. name and detail are two fields that are used to store the name of the author and the citation sent by the author respectively.
  • serializer.py: create serializer.py inside the main folder. here is the serializer for the react model. serializers are basically used to convert complex data into native python datatypes which can then be easily represented in json (which we are going to use in react i.e. on the client side).
  • views.py: here is views.py in which we can create our method like get, put, post, delete. I created get and post using django’s class-based views. in the get method, we return data from the model by calling react.objects.all() and then using list comprehension to convert the author and citations from it to the python dictionary. In the post method, we’re simply saving the data without passing the data to reactserializer().It’s time to define the api endpoint. the endpoint of an api is the url where our client will access to consume data from the server. it’s usually where our resources (database and other programming functions) live.

step 6:

  • urls.py: here is the main urls.py from the project listing. localhost:8000/wel/ is the endpoint of our reactview.

Step 7: There are some changes in the settings.py file listed below

  1. add rest_framework , core, corsheaders to installed applications
  2. add corsheaders.middleware.corsmiddleware to middleware list.
  3. create a dictionary assigned to the rest_framework variable in which you insert ‘default_permission_classes’: [ ‘rest_framework.permissions.allowany’ ]
  4. assign the variable cors_origin_allow_all = true

You might be thinking of the corsheaders package. actually, the cors header bundle is used to tell the browser that the web application running on one origin access the selected resources from a different origin.

Now let’s go back to the final part of our back-end. run the following commands in the terminal.

  • This command is used to detect changes made to the database.
  • this command applies those changes to the database.
  • to create a super user who will be the administrator of the entire application.
  • this command will run the server and the server must always be in the running state.

or

open the web browser of your choice (chrome is recommended) and search for localhost:8000/wel/

Screenshotfrom20200719011939-660x375.png

configure the front-end: There is no limit to make the front-end folder in the same directory as the back-end folder. furthermore, there is no need to create a virtual environment to react. use the following commands to prepare for the react app. using bootstrap to design and improve the look and feel, jquery is for dependencies with bootstrap.

axios is the main tool to connect back-end with front-end. all requests will be sent to the server (back-end) with the help of axios.

inside our quote/src/app.js:

output: after running npm start the react development server will be started and by default it can be seen on localhost:3000

Screenshotfrom20200719015918-660x370.png

app.js: now we need to get data from the server using axios. the componentdidmount method is called when the component is rendered. this is the right time to request a server for data. we have used axios in this method to store the data in a state fetched from the server and then rendered with the help of a map in javascript.

output: Since there is no data to display, fill in some data in the database from the server side.

Screenshotfrom20200719022256.pngScreenshotfrom20200731202854.png

app.js: Now the only part left of this project is to create a form so that the user can fill in the data from the client side, which is the correct way to do it. here is the form that sends a response from the client side along with bootstrap.

output: the form will call handlesubmit which in turn uses the post method and sends the response to the endpoint http://localhost:8000/wel/. the renderswitch() is used to pass the index of the array which, in turn, returns the color of the bootstrap class name.

Screenshotfrom20200719103828.png

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button