Full Stack Project with React.js and Django (Task Manager Application)

5 min read 1 year ago
Published on Aug 04, 2024 This response is partially generated with the help of AI. It may contain inaccuracies.

Table of Contents

Introduction

In this tutorial, we will build a task manager application using Django for the backend and React.js for the frontend. This application will allow users to create, edit, delete, and manage tasks effectively. By following this step-by-step guide, you will learn how to set up Django REST framework for API functionality and connect it with a React frontend using Axios for data management.

Chapter 1: Frontend Build with React

Setting Up the Environment

  1. Install Prerequisites

    • Ensure you have Python 3.5 or higher and Node.js installed.
    • Test installations:
      python --version
      node --version
      
  2. Create Project Directory

    • Open your command prompt/terminal.
    • Create a new directory:
      mkdir django_react_app
      cd django_react_app
      
  3. Set Up Virtual Environment

    • Create and activate a virtual environment:
      pip install virtualenv
      virtualenv venv
      source venv/bin/activate  # For macOS/Linux
      venv\Scripts\activate     # For Windows
      
  4. Install Django

    • Install Django in the virtual environment:
      pip install django
      
  5. Create Django Project and App

    • Create a new Django project:
      django-admin startproject backend
      cd backend
      django-admin startapp todo
      
  6. Run Initial Migrations

    • Apply the initial migrations:
      python manage.py migrate
      
  7. Set Up Django Admin

    • Open backend/settings.py and add 'todo' to INSTALLED_APPS.
    • Create a model for tasks in todo/models.py:
      from django.db import models
      
      class Todo(models.Model):
          title = models.CharField(max_length=120)
          description = models.CharField(max_length=500)
          completed = models.BooleanField(default=False)
      
          def __str__(self):
              return self.title
      
  8. Register Model in Admin

    • In todo/admin.py, register the model:
      from django.contrib import admin
      from .models import Todo
      
      class TodoAdmin(admin.ModelAdmin):
          list_display = ('title', 'description', 'completed')
      
      admin.site.register(Todo, TodoAdmin)
      
  9. Create Superuser

    • Create a superuser to access the admin:
      python manage.py createsuperuser
      
  10. Run the Server

    • Start the Django development server:
      python manage.py runserver
      

Setting Up Django REST Framework

  1. Install Django REST Framework

    • Install Django REST framework and CORS headers:
      pip install djangorestframework django-cors-headers
      
  2. Configure Django Settings

    • Add 'rest_framework' and 'corsheaders' to INSTALLED_APPS in settings.py.
    • Add CORS middleware in the MIDDLEWARE settings:
      MIDDLEWARE = [
          ...
          'corsheaders.middleware.CorsMiddleware',
          ...
      ]
      
  3. Set Up CORS

    • Allow CORS for React (port 3000):
      CORS_ALLOWED_ORIGINS = [
          "http://localhost:3000",
      ]
      
  4. Create Serializers

    • Create todo/serializers.py:
      from rest_framework import serializers
      from .models import Todo
      
      class TodoSerializer(serializers.ModelSerializer):
          class Meta:
              model = Todo
              fields = '__all__'
      
  5. Create API Views

    • In todo/views.py, create viewsets:
      from rest_framework import viewsets
      from .models import Todo
      from .serializers import TodoSerializer
      
      class TodoViewSet(viewsets.ModelViewSet):
          queryset = Todo.objects.all()
          serializer_class = TodoSerializer
      
  6. Configure URLs

    • In backend/urls.py, add the API routes:
      from django.urls import path, include
      from rest_framework.routers import DefaultRouter
      from todo.views import TodoViewSet
      
      router = DefaultRouter()
      router.register(r'tasks', TodoViewSet)
      
      urlpatterns = [
          path('api/', include(router.urls)),
      ]
      
  7. Test the Backend API

    • Access http://localhost:8000/api/tasks/ to ensure the API is working.

Chapter 2: Frontend Build with React

Setting Up React App

  1. Create React App

    • Create a new React app:
      npx create-react-app frontend
      cd frontend
      
  2. Install Bootstrap and Reactstrap

    • Install Bootstrap and Reactstrap for UI components:
      npm install bootstrap reactstrap
      
  3. Import Bootstrap in src/index.js

    import 'bootstrap/dist/css/bootstrap.min.css';
    

Building the Task Manager UI

  1. Set Up State and Functions in App.js

    • In src/App.js, set up the initial state:
    import React, { Component } from 'react';
    import axios from 'axios';
    
    class App extends Component {
        constructor(props) {
            super(props);
            this.state = {
                tasks: [],
                newTask: { title: '', description: '', completed: false },
            };
        }
    
  2. Fetch Tasks from API

    • Use componentDidMount to fetch tasks:
    componentDidMount() {
        this.refreshList();
    }
    
    refreshList = () => {
        axios.get('http://localhost:8000/api/tasks/')
            .then(res => this.setState({ tasks: res.data }))
            .catch(err => console.error(err));
    }
    
  3. Handle Task Creation and Deletion

    • Create methods for adding and deleting tasks:
    handleAddTask = () => {
        axios.post('http://localhost:8000/api/tasks/', this.state.newTask)
            .then(() => this.refreshList())
            .catch(err => console.error(err));
    }
    
    handleDeleteTask = (id) => {
        axios.delete(`http://localhost:8000/api/tasks/${id}/`)
            .then(() => this.refreshList())
            .catch(err => console.error(err));
    }
    
  4. Render the Task List and Form

    • Build the task list and form in the render method:
    render() {
        return (
            <div className="container">
                <h1>Task Manager</h1>
                <input type="text" placeholder="Task Title" onChange={e => this.setState({ newTask: { ...this.state.newTask, title: e.target.value } })} />
                <input type="text" placeholder="Description" onChange={e => this.setState({ newTask: { ...this.state.newTask, description: e.target.value } })} />
                <button onClick={this.handleAddTask}>Add Task</button>
                <ul>
                    {this.state.tasks.map(task => (
                        <li key={task.id}>
                            {task.title} - {task.completed ? "Completed" : "Incomplete"}
                            <button onClick={() => this.handleDeleteTask(task.id)}>Delete</button>
                        </li>
                    ))}
                </ul>
            </div>
        );
    }
    

Testing the React Frontend

  1. Run the React App

    • Start the React development server:
      npm start
      
  2. Interact with the Application

    • Use the UI to add, view, and delete tasks.
    • Ensure that data is being sent to and received from the Django backend correctly.

Conclusion

In this tutorial, you have successfully built a task manager application using Django and React. You learned how to set up the backend API with Django REST framework and connect it with a React frontend using Axios for data management. This project serves as a solid foundation for understanding full-stack development and can be expanded with additional features such as user authentication, more complex UI components, and enhanced task management capabilities.