Tutorial on Building a Django and React Web App – Including Authentication, Database Management, Deployment, and More

Posted by


In this tutorial, we will be building a full-stack web application using Django and React. We will cover topics such as authentication, databases, deployment, and more. By the end of this tutorial, you will have a basic understanding of how to create a web application with Django and React.

Before we get started, make sure you have the following tools installed on your computer:

  • Python
  • Node.js
  • npm
  • Django
  • Django REST framework
  • React

Let’s begin by setting up our Django backend.

Step 1: Create a new Django project

Open your terminal and run the following command to create a new Django project:

django-admin startproject myproject

Navigate to the project directory:

cd myproject

Step 2: Create a new Django app

Next, create a new Django app by running the following command:

python manage.py startapp myapp

Add the app to the list of installed apps in your settings.py file:

INSTALLED_APPS = [
    ...
    'myapp',
]

Step 3: Set up a PostgreSQL database

Install the psycopg2 package by running:

pip install psycopg2

Update your database settings in settings.py:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'mydatabase',
        'USER': 'myuser',
        'PASSWORD': 'mypassword',
        'HOST': 'localhost',
        'PORT': '5432',
    }
}

Step 4: Create models and migrations

Define your models in the models.py file of your app:

from django.db import models

class User(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField(unique=True)
    password = models.CharField(max_length=100)

Run the following commands to create and apply migrations:

python manage.py makemigrations
python manage.py migrate

Step 5: Set up Django REST framework

Install the Django REST framework by running:

pip install djangorestframework

Add the REST framework to your installed apps in settings.py:

INSTALLED_APPS = [
    ...
    'rest_framework',
]

Create a serializer for your model in a serializers.py file:

from rest_framework import serializers
from .models import User

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'

Create views for your API endpoints in a views.py file:

from rest_framework import viewsets
from .models import User
from .serializers import UserSerializer

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

Set up your URLs in your urls.py file:

from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import UserViewSet

router = DefaultRouter()
router.register(r'users', UserViewSet)

urlpatterns = [
    path('', include(router.urls)),
]

Step 6: Create a login and registration endpoint

Add the following code to your views.py file:

from rest_framework import generics
from rest_framework.response import Response
from rest_framework.authtoken.models import Token
from django.contrib.auth.models import User
from rest_framework.decorators import api_view

@api_view(['POST'])
def register(request):
    data = request.data
    user = User.objects.create_user(username=data['username'], password=data['password'])
    token, _ = Token.objects.get_or_create(user=user)
    return Response({'token': token.key})

@api_view(['POST'])
def login(request):
    data = request.data
    user = User.objects.filter(username=data['username']).first()
    if user is None:
        return Response({'error': 'User not found'}, status=400)
    if not user.check_password(data['password']):
        return Response({'error': 'Invalid password'}, status=400)
    token, _ = Token.objects.get_or_create(user=user)
    return Response({'token': token.key})

Update your urls.py file:

from .views import register, login

urlpatterns = [
    ...
    path('register/', register),
    path('login/', login),
]

That’s it for the Django backend! Now let’s move on to setting up our React frontend.

Step 7: Set up a React project

Create a new React project by running the following command:

npx create-react-app myapp

Navigate to the project directory:

cd myapp

Step 8: Install axios

Install Axios for making API requests:

npm install axios

Step 9: Create a login and register form

Create a login form in your App.js file:

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

function App() {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');

  const handleLogin = async () => {
    const response = await axios.post('http://localhost:8000/login/', { username, password });
    console.log(response.data);
  }

  return (
    <div className="App">
      <input type="text" placeholder="Username" onChange={(e) => setUsername(e.target.value)} />
      <input type="password" placeholder="Password" onChange={(e) => setPassword(e.target.value)} />
      <button onClick={handleLogin}>Login</button>
    </div>
  );
}

export default App;

Create a register form in your App.js file:

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

function App() {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');

  const handleRegister = async () => {
    const response = await axios.post('http://localhost:8000/register/', { username, password });
    console.log(response.data);
  }

  return (
    <div className="App">
      <input type="text" placeholder="Username" onChange={(e) => setUsername(e.target.value)} />
      <input type="password" placeholder="Password" onChange={(e) => setPassword(e.target.value)} />
      <button onClick={handleRegister}>Register</button>
    </div>
  );
}

export default App;

Step 10: Run the Django backend and React frontend

Start your Django server by running:

python manage.py runserver

Start your React app by running:

npm start

Navigate to http://localhost:3000 in your browser to see your React app in action.

That’s it! You have now created a full-stack web application using Django and React. Feel free to explore more features and functionalities to enhance your application. Happy coding!

0 0 votes
Article Rating
46 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@AliHassan-hf6uq
30 days ago

hello tim ,firstlly thank you soo much about this special course,just i have one question,
i want to make nested page home and this page has ProtectedRoute , i try ta make that in the normal steps but it does not work ,can you give us some information or any person can help me,thank you .

@rakshithr3888
30 days ago

Seeing "AxiosError: Network Error" at line 21 of Form.jsx. "const res = await api.post(route, { username, password })".
Please help @Techwithtim

@jamespeters1617
30 days ago

This token thing is super useful thanks

@jamespeters1617
30 days ago

You bot on the discord is confused don’t think he’ll get you any message either, but well done on your videos and maybe I’ll hear from you. Or keep checking in, the project is getting better everyday. Thanks Tim, your awesome

@jamespeters1617
30 days ago

I’m sure busy any way or will even read these comments, but who know maybe you have a good mom scanning your messages. Lol

@tembomedia6902
30 days ago

I came to realize late in my 30s that I have sever ADHD, can't complete a coding project. I have never completed a coding project in my life. I have always wanted to learn coding, this is the 1st project I have completed and pushed to Git. Thank you.

@abidusage9765
30 days ago

I'd like to know in which way we can implement the relation one to many to the note

@HarleyCarroll-y9y
30 days ago

I found the tutorial to be excellent! The video provided insights for individuals interested in developing a comprehensive web application using Django and React technologies. I particularly appreciated the explanation you provided regarding authentication procedures and database management processes step by step in addition, to deployment techniques. The presentation was clear and easy to follow for beginners venturing into these technologies for the time. It was refreshing to see that you covered not coding aspects but also delved into environment configurations which are often overlooked in similar tutorials. I appreciate the content; I can't wait to see more videos with in depth explanations, in the future!

@sheryllee621
30 days ago

hi, how do i view the info created on the database? e.g. if i wanted to manage the tasks created, etc?

@emirbuyukceylan7280
30 days ago

Thank you so much Tim. This is unbelievable. thank you for your efforts.

@rohollaahmadzadeh7201
30 days ago

I can't thank you enough, this video saved me

@arielkergall9372
30 days ago

Hi! I have been following you really good tuthorial, but i'm in a trouble. I have create two users but I can't get the token, it says " No active account found with the given credentials" I dont know why, coz users have been created and I can see them. Do you think you can helpme please?

@arnoldmarcus3634
30 days ago

I know how to make python scripts and programs for engineering and modeling that just working in the IDE, but finding something that really explains the the leap to app deployment has been hard, thanks for this video. It's a gem. Most search results are more high level and don't explain the execution. Thanks for this.

@sujanrathod8757
30 days ago

Can a beginner watch

@felipelopes5649
30 days ago

Muito obrigado! Era o que precisava para começar. Parabéns por compartilhar seu conhecimento conosco. Grato.😁

@manohartimothy5825
30 days ago

It was enjoyable and very well-explained. But I am facing a problem with creating a Note. Submitting a Note gives me an Error message like AxiosError: Request failed with status code 405 and "detail": "Authentication credentials were not provided." Please explain why?

@kanodekoubillybrown3025
30 days ago

why not using process.env for getting environment variables ?

@arielduarte719
30 days ago

Thank you so much for this great tutorial, I learned a lot of things new stuff!.

@justanothertechguy
30 days ago

Any one getting an error when running the npm create command

@arghosinha1424
30 days ago

It would be so great if you could put down all the links that you are referring to while make the projects.