Beginner’s Guide: React Django CRUD Tutorial – Master React and Django in just 1 Hour

Posted by


React and Django are two powerful technologies that are often used together to build modern web applications. In this tutorial, we will walk you through building a CRUD (Create, Read, Update, Delete) application using React and Django. This tutorial is aimed at beginners who are looking to learn how to use React and Django together.

Step 1: Setting up your environment

Before we get started with building our CRUD application, we need to set up our development environment. Make sure you have Node.js installed on your machine, as well as Python and Django. You can install Node.js by visiting the official website and downloading the installer. For Django, you can install it using pip by running the following command:

pip install Django

Step 2: Creating a Django project

The first step is to create a new Django project. Open your terminal and run the following command to create a new project:

django-admin startproject crudApp

This will create a new folder called crudApp with all the necessary files and folders for a Django project. Navigate to this folder and run the following command to start the Django server:

python manage.py runserver

Visit http://localhost:8000 in your browser to see the default Django welcome page.

Step 3: Creating a Django app

Next, we need to create a new Django app within our project. Run the following command in your terminal to create a new app called backend:

python manage.py startapp backend

This will create a new folder called backend with all the necessary files for our Django app.

Step 4: Setting up the Django models

In our Django app, we need to define the models for our CRUD operations. Open the models.py file inside the backend folder and define a simple model for our application. For example, we can define a Product model with fields like name, price, and description:

from django.db import models

class Product(models.Model):
    name = models.CharField(max_length=100)
    price = models.FloatField()
    description = models.TextField()

After defining the model, run the following command in your terminal to create the necessary database tables:

python manage.py makemigrations
python manage.py migrate

Step 5: Setting up the Django views

Next, we need to create views to handle the CRUD operations for our Product model. Open the views.py file inside the backend folder and define the views for listing, creating, updating, and deleting products:

from rest_framework import viewsets
from .models import Product
from .serializers import ProductSerializer

class ProductViewSet(viewsets.ModelViewSet):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer

Step 6: Setting up the Django serializers

We also need to create serializers to convert the model instances to JSON and vice versa. Create a new file called serializers.py inside the backend folder and define a serializer for our Product model:

from rest_framework import serializers
from .models import Product

class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = '__all__'

Step 7: Setting up the Django URLs

Finally, we need to define the URLs for our views. Open the urls.py file inside the backend folder and define the URL patterns for our Product views:

from rest_framework.routers import DefaultRouter
from .views import ProductViewSet

router = DefaultRouter()
router.register(r'products', ProductViewSet)

urlpatterns = router.urls

Step 8: Setting up the React application

Now that we have set up our Django backend, let’s move on to setting up our React frontend. Create a new React app using create-react-app by running the following command in your terminal:

npx create-react-app frontend

This will create a new folder called frontend with all the necessary files for a React app. Navigate to this folder and run the following command to start the React server:

npm start

Visit http://localhost:3000 in your browser to see the default React welcome page.

Step 9: Creating React components

Next, we need to create React components to interact with our Django backend. Create a new file called ProductList.js inside the src folder and define a component to list all the products:

import React, { useState, useEffect } from 'react';
import axios from 'axios';

const ProductList = () => {
    const [products, setProducts] = useState([]);

    useEffect(() => {
        axios.get('http://localhost:8000/api/products/')
            .then(response => setProducts(response.data))
            .catch(error => console.error(error));
    }, []);

    return (
        <div>
            <h1>Products</h1>
            <ul>
                {products.map(product => (
                    <li key={product.id}>
                        {product.name} - ${product.price}
                    </li>
                ))}
            </ul>
        </div>
    );
};

export default ProductList;

Step 10: Making API requests in React

To interact with our Django backend, we need to make API requests from our React components. We can use the axios library to make HTTP requests. Install axios by running the following command in your terminal:

npm install axios

Now, we can make API requests to fetch the list of products from our Django backend using the following code:

import axios from 'axios';

axios.get('http://localhost:8000/api/products/')
    .then(response => console.log(response.data))
    .catch(error => console.error(error));

Step 11: Wrapping up

Congratulations! You have successfully built a CRUD application using React and Django. In this tutorial, you learned how to set up a Django backend with models, views, serializers, and URLs, as well as how to create a React frontend with components to interact with the Django backend. This tutorial is a great starting point for beginners looking to learn how to use React and Django together. Happy coding!

0 0 votes
Article Rating
38 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@tomahocbc963
2 months ago

please can you add authenticaion, login, logout etc..

@Deus-lo-Vuilt
2 months ago

Thank you, I was just looking for a video like this

@FarhanAlly
2 months ago

hey pedro i was just requesting if you can clarify for the following things.. i am just a react guy and recently i have seen your firebase tutorial and i was following over them my question is can i totally use firebase as my solid backend because i have no knowledge about backend language… the other thing is can i partially usee firebase only when it comes to authenticatication part and use RTK querry of which i know it better fro thee CRUD operation . thanks

@rangabharath4253
2 months ago

Awesome

@charliemiddleton9918
2 months ago

WE NEED MORE
is vite really necessary?

@janice5083
2 months ago

35:50

@janice5083
2 months ago

help so in order to connect django and react i just need to use the corsheaders stuff and the rest framework?

@xzex2609
2 months ago

this was very helpful but actually there are a lots of problems that needed to be taken care of , Like
the input fields must have been two way bounded so you can control the field after creating the book (clean them).
the back end needed to check if the book is already exist and don't let you add more.
the front end needed to check if the response is ok then add the contents so the empty book does not added when the database reject that the book is already exists.

the backend needed to check if the both of the fields are provided then add them to the database

I add some of the solutions
if not title and not release_year:

return Response({'detail': 'the title and the year is not provided'}, status=status.HTTP_400_BAD_REQUEST)
if Book.objects.filter(title=title, release_year=release_year):

return Response({'detail': 'Book already exist'}, status=status.HTTP_400_BAD_REQUEST)

add value field in the input for twoway bounding and settitle('') setReleaseYear('') in every functions the it needs

and check the response
if (response.ok) {

const data = await response.json();

setBooks(b => […b, data]);

// Reset the input fields after adding the book

setTitle('');

setReleaseYear('');

} else {

const errorData = await response.json();

console.log("Error:", errorData);

alert("This book already exists in the database.");

}

and lastly use turnary opetator instead of if else

setBooks(b => b.map(book => (book.id === id ? data : book)));

@nileshkanjariya3950
2 months ago

Django advance course

@mansbjork5721
2 months ago

This helped a lot. As a student, I'll be making a web app with React and Django and this helps a lot.
Do you, by chance, know about dockerizing an app like this (using compose.yaml)?

@adamlahchimi-zb9rc
2 months ago

the linkdin link doesnt work

@xzex2609
2 months ago

more django stuff

@xzex2609
2 months ago

I add some functionality to the create end point not to let add books when it is available in the data base and when the title is null I will copy the code for others.
@api_view(['POST'])

def create_book(request):

data = request.data

title = data.get('title')

release_year = data.get('release_year')

if not title and not release_year:

return Response({'detail': 'the title and the year is not provided'}, status=status.HTTP_400_BAD_REQUEST)

if Book.objects.filter(title=title, release_year=release_year):

return Response({'detail': 'Book already exist'}, status=status.HTTP_400_BAD_REQUEST)

serializer = BookSerializer(data=data)

if serializer.is_valid():

serializer.save()

return Response(serializer.data, status=status.HTTP_201_CREATED)

return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

@xzex2609
2 months ago

this was great . simple . right to the point. good stuff

@dev-akeel
2 months ago

🤔 I have been watching you for more than a couple of years, why do you put those unnecessary spaces in the jsx? and when prettier tries to format your code you just remove that formatted {" "}.

@pinyin1
2 months ago

Wow amazing

@CalderonEimannJoshuaL.
2 months ago

Can you make a video for chat app system using django? Im stuck in implementing the chat app😢

@bahdcoder
2 months ago

please make more django projects

@bahdcoder
2 months ago

as i saw this video and i started praying for you.. thank you pedro

@godofwar8262
2 months ago

Hey will you make a backend series with javascript