Athtripathi
Geek Culture
Published in
7 min readMay 27, 2021

--

Using Django with react: creating best frontend and backend combination

Hello everyone(go directly to the coding part to know how to combine Django and react),

So when I started learning web development I learned HTML, CSS, and Javascript but I was a bit confused because I don’t know what I should learn next or Html, CSS and javascript are enough. Then I start researching, I come across the term like Frontend and Backend.

On doing further research I come to know about frontend and backend frameworks.

Then I come to know there are tonnes of frameworks and I am having difficulty in choosing the right framework.

When I learned what backend and frontend mean, I thought “Backend is something that looks cooler and frontend can be done with help of HTML and CSS, so I will learn backend first”

When I saw the list of most popular backends, my mind gets buzzed and I find it hard to choose something suitable for me.

Then I saw Django, which is python based Backend framework, I was an expert in python so Django was the most suitable thing for me.

I go on youtube, and search “Django tutorials that will make me god of backends” and I found some cool tutorials, which didn’t make me god but I become good at Django.

Django is easy to learn and very easy to handle, if you know python then learn Django and if you don’t know python then learn python first and then Django, but learn Django anyhow because it is one of the most popular and best backend frameworks.

Companies like Facebook are shifting their backend from PHP to Django and yes Instagram uses Django as its backend framework.

And here is a gift for you readers, tutorials from which I learn Django and another tutorial that I found amazing.

From which I learn coding and for Hindi speakers A whole playlist with 2 projects.

After I learned Django, I made a project of online school form submission for practice.

Then I come to chapter 2, the FRONTEND.

Choosing a front-end framework is harder than choosing a backend framework.

There are a lot of great choices, I stuck in 3 frameworks that are Angular JS, Vue JS, and React JS.

All 3 are cool and really popular frameworks and each has its own separate fanbase.

After a tonne of research and analysis, I chose to REACT.

React is a cool framework and the thing I like, most about it is its division of components.

I love react and found it easy to learn and use.

I go on youtube again and search for react tutorial, there are a tonne of tutorials for learning react and I didn’t learn from any specific video or playlist, you can choose any but if you ask for my recommendation then I will say go with “learning with mosh” tutorial.

There is one more plus point in learning react and it is that you can learn react native after learning react, react native is a hybrid mobile app making framework, you can easily learn it if you know react and you can make good apps with it, although you can’t make very complex apps only native apps.

So we discussed frontend and backend, and what are good frameworks to learn.

Now let see how we can combine both of these frameworks to create magic.

A complete website can be divided into 4 parts.

Database — — — — — ->backend — — — — — — — — ->API(Rest api) — — — — — →Frontend.

If you know Django, then the database and backend part is in your hand, for API you need to know Django REST, which hardly takes an hour to master, and for frontend, react is your best sword.

Let dive into the coding part.

CODING PART(DON’T SKIP):-

Now let make our backend first. For demonstration, I will use the Login system of a project I made for practice.

I am assuming now you learned Django and react.

This project is an online assignment managing system.

As you can see, a user has 3 credentials to login(username is a unique code generated by the backend).

First import a decorator called “api_view” and “Response” to return a response from API to frontend, Last but not least you need to import database references called models in Django(We will only use the User model).

In the settings.py file, add the following lines:

Code:

CORS_ORIGIN_ALLOW_ALL=True #Add this in the bottom before AUTH_MODEL

ALLOWED_HOSTS = [“masterassignment.herokuapp.com”,”127.0.0.1"]

Now let dive into frontend part and see how we will send request from reactJS.

Code:

getCookie(name) {

var cookieValue = null;

if (document.cookie && document.cookie !== ‘’) {

var cookies = document.cookie.split(‘;’);

for (var i = 0; i < cookies.length; i++) {

var cookie = cookies[i].trim();

// Does this cookie string begin with the name we want?

if (cookie.substring(0, name.length + 1) === (name + ‘=’)) {

cookieValue = decodeURIComponent(cookie.substring(name.length + 1));

break;

}

}

}

return cookieValue;

}

Add this line of code inside every file of reactJS or add this in one file and import function in every file, it is all up to you.

Now let send the request to the backend:

handleSubmit(e){

e.preventDefault();

var csrftoken = this.getCookie(‘csrftoken’);

var url=”https://your.example.link"

fetch(url,{

‘method’:’POST’,

“headers”:{

“Content-type”:”application/json”,

“X-CSRFToken”:csrftoken

},

“body”:JSON.stringify([your example data])

})

You can see a variable “csrftoken”, we get its value from the function we made above.

We are using fetch() here, you can use Axios to but for this, we will use fetch().

We need to add “csrftoken” in the “X-CSRFToken” of the “headers” portion.

Now the interesting part is sending the data.

As you can see in the “body” portion, we will add an array that contains every single data point that is entered by the user in the form, like password, username, roles, school code.

Now we need to convert the array into the string by using JSON.stringify().

Now it is the process of sending requests.

Now let get to the backend where we will handle the request.

Let see the backend portion:

Now we first add decorator api_view with POST(you can replace it with GET or DELETE according to your request method).

Now everything is piece of cake now.

To access each data point from the array you just need to use “request.data[]”

Like:

request.data[3]

or

user=User.objects.get(UserName=request.data[0],password=request.data[1],SchoolCode=request.data[2],Role=”teacher”)

and add the datapoint index of the array between the square bracket.

Now apply your database query and send the response back to the frontend using “Response()”(note that, you need to send data in curly braces format as shown)

Like(this is my most favorite method to return response):

return Response({“username”:user.UserName,”password”:request.data[1],

“SchoolCode”:user.SchoolCodeAdmin,”TeacherCode”:user.SchoolCode,”role”:

“teacher”,”ID”:user.userID})

Using curly braces and returning responses in key-value format or can be called Json format.

Now the last part of the process is handling response. It is similar to handling any API response with nothing rocket science in it.

Like:

.then(resp=>resp.json()).then(res=>{

//Whatever you want to do with response like here I set data to local storage and reload screen and yes, I use some conditions to

}

Use .then() and convert the response into JSON and do anything you want.

This is all process to get the deadliest combination of frontend and backend.

Follow me for more and my tutorial will be on react native + Django.

If you want to buy my project code then Here is the link you can pay any amount you want and the minimum payment is $1(code is not self-explanatory though), You can support me by buying my codes to keep me motivated.

For any query DM me on Instagram on my business account: My Instagram.

--

--

Athtripathi
Geek Culture

I am Ath Tripathi. I am now a freelance blogger |full-stack developer| Teenager | AI/ML learner | Data science enthusiast | AR/VR,metaverse enthusiast