Full Stack Project with React.js and Django (Task Manager Application)
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
-
Install Prerequisites
- Ensure you have Python 3.5 or higher and Node.js installed.
- Test installations:
python --version node --version
-
Create Project Directory
- Open your command prompt/terminal.
- Create a new directory:
mkdir django_react_app cd django_react_app
-
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
- Create and activate a virtual environment:
-
Install Django
- Install Django in the virtual environment:
pip install django
- Install Django in the virtual environment:
-
Create Django Project and App
- Create a new Django project:
django-admin startproject backend cd backend django-admin startapp todo
- Create a new Django project:
-
Run Initial Migrations
- Apply the initial migrations:
python manage.py migrate
- Apply the initial migrations:
-
Set Up Django Admin
- Open
backend/settings.pyand add'todo'toINSTALLED_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
- Open
-
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)
- In
-
Create Superuser
- Create a superuser to access the admin:
python manage.py createsuperuser
- Create a superuser to access the admin:
-
Run the Server
- Start the Django development server:
python manage.py runserver
- Start the Django development server:
Setting Up Django REST Framework
-
Install Django REST Framework
- Install Django REST framework and CORS headers:
pip install djangorestframework django-cors-headers
- Install Django REST framework and CORS headers:
-
Configure Django Settings
- Add
'rest_framework'and'corsheaders'toINSTALLED_APPSinsettings.py. - Add CORS middleware in the
MIDDLEWAREsettings:MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware', ... ]
- Add
-
Set Up CORS
- Allow CORS for React (port 3000):
CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", ]
- Allow CORS for React (port 3000):
-
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__'
- Create
-
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
- In
-
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)), ]
- In
-
Test the Backend API
- Access
http://localhost:8000/api/tasks/to ensure the API is working.
- Access
Chapter 2: Frontend Build with React
Setting Up React App
-
Create React App
- Create a new React app:
npx create-react-app frontend cd frontend
- Create a new React app:
-
Install Bootstrap and Reactstrap
- Install Bootstrap and Reactstrap for UI components:
npm install bootstrap reactstrap
- Install Bootstrap and Reactstrap for UI components:
-
Import Bootstrap in
src/index.jsimport 'bootstrap/dist/css/bootstrap.min.css';
Building the Task Manager UI
-
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 }, }; } - In
-
Fetch Tasks from API
- Use
componentDidMountto 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)); } - Use
-
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)); } -
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
-
Run the React App
- Start the React development server:
npm start
- Start the React development server:
-
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.