Build a Powerful Task Management System with Django and REST API

Build a Powerful Task Management System with Django and REST API

Overview:

Design and implement a RESTful API for a simple Task Management System.

The system allows users to manage their tasks by performing CRUD (Create, Read, Update, Delete)
operations.

The tasks have basic properties such as title, description, status, priority, and due date.

Users can create, update, view, and delete tasks.

The API should be designed to allow future extensions, such as adding features like user authentication, assigning tasks to users, etc.

Requirements

Project Setup:

Create a Django project and a Django app dedicated to the task management functionality.

Models Design:

Task Model: Design a model named Task with the following fields:

  • title: A short title for the task (e.g., “Fix bug in module X”).
  • description: A detailed description of the task.
  • status: The status of the task (e.g., “To Do”, “In Progress”, “Completed”). Use a choice field.
  • priority: The priority level of the task (e.g., “Low”, “Medium”, “High”). Use a choice field.
  • due_date: The date by which the task should be completed.
  • created_at: The timestamp when the task was created (auto-generated).
  • updated_at: The timestamp when the task was last updated (auto-generated).

Design consideration: Use appropriate field types, and consider adding any additional fields that may be relevant.

REST API Design:

Implement RESTful endpoints for the Task Management System using Django
REST Framework (DRF).

Endpoints:

  • GET /tasks/: Retrieve a list of tasks.
  • GET /tasks//: Retrieve details of a specific task by its ID.
  • POST /tasks/: Create a new task.
  • PUT /tasks//: Update an existing task.
  • DELETE /tasks//: Delete a specific task.

Ensure the API follows REST conventions and is well-documented.

Views & Serializers:

  • Use ModelViewSet to implement the views for the Task model.
  • Create a TaskSerializer to define the serialization and deserialization of Task objects.
  • Ensure that the API handles various input formats (e.g., JSON).

Design Patterns & Object-Oriented Principles:

  • Implement relevant design patterns (e.g., Factory, Singleton) in the views, models, or serializers where appropriate.
  • Ensure the code adheres to object-oriented principles like encapsulation, inheritance, and polymorphism.

Error Handling & Logging:

  • Implement comprehensive error handling in the API. Ensure meaningful error messages are returned for invalid requests (e.g., 400 Bad Request for invalid data, 404 Not Found for non-existent tasks).
  • Set up logging to record errors, warnings, and other significant events. Use Django’s logging framework to log these events to a file.
  • Ensure that sensitive information is not exposed in the logs.

Task Management System – Django REST Framework Implementation

Project Setup

Create Django Project:

django-admin startproject task_management
cd task_management

You can find details about these steps in the Django tutorial guide.

Create Django App:

python manage.py startapp tasks

Install Django REST Framework:

Add rest_framework to the INSTALLED_APPS in settings.py.

INSTALLED_APPS = [
    ...,
    'rest_framework',
    'tasks',
]

Models Design of Task Model

Define the Task model in tasks/models.py:

from django.db import models

class Task(models.Model):
    STATUS_CHOICES = [
        ('todo', 'To Do'),
        ('in_progress', 'In Progress'),
        ('completed', 'Completed'),
    ]

    PRIORITY_CHOICES = [
        ('low', 'Low'),
        ('medium', 'Medium'),
        ('high', 'High'),
    ]

    title = models.CharField(max_length=255)
    description = models.TextField()
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='todo')
    priority = models.CharField(max_length=20, choices=PRIORITY_CHOICES, default='medium')
    due_date = models.DateField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.title

Migrate the Models:

python manage.py makemigrations
python manage.py migrate

REST API Design

Task Serializer:

Create a serializer for the Task model in tasks/serializers.py:

from rest_framework import serializers
from .models import Task

class TaskSerializer(serializers.ModelSerializer):
    class Meta:
        model = Task
        fields = '__all__'

TaskSerializer acts as an intermediate between the Django model and the outside world (like a mobile app or web browser).

It converts the Task model data to standard data format (usually JSON) that can be understood by other applications.

Task ViewSet:

Implement the TaskViewSet using ModelViewSet in tasks/views.py:

from rest_framework import viewsets
from .models import Task
from .serializers import TaskSerializer

class TaskViewSet(viewsets.ModelViewSet):
    queryset = Task.objects.all()
    serializer_class = TaskSerializer

URL Routing:

Define the URL routes in tasks/urls.py:

from rest_framework.routers import DefaultRouter
from .views import TaskViewSet

router = DefaultRouter()
router.register(r'tasks', TaskViewSet, basename='task')

urlpatterns = router.urls

The method router.register() connects the TaskViewSet to the tasks endpoint. It means it creates the following endpoints. You don’t have to create any endpoints explicitly.

  • GET /tasks/: Lists all tasks.
  • GET /tasks/<id>/: Retrieves details of a specific task.
  • POST /tasks/: Creates a new task.
  • PUT /tasks/<id>/: Updates an existing task.
  • DELETE /tasks/<id>/: Deletes a specific task.

Here we are using different HTTP methods in REST API design.

Include the tasks app URLs in the main urls.py of the project:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('tasks.urls')),
]

Design Patterns & Object-Oriented Principles

  • Encapsulation:
    The Task model encapsulates all properties of a task.
  • Polymorphism:
    The ModelViewSet handles different HTTP methods (GET, POST, PUT, DELETE) based on the request.

Error Handling & Logging

  • Error Handling
    Customize error handling within the views or use DRF’s default error handling mechanism.
  • Logging
    Configure logging in settings.py:
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': 'task_management.log',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'level': 'DEBUG',
            'propagate': True,
        },
    },
}

Final Touches

  • Testing: Test the API using tools like Postman or Django’s built-in testing tools.
  • Documentation: Use tools like Swagger or DRF’s built-in API documentation to document the API.

To track all the tasks, you can customize the Django admin panel.

This setup provides a robust starting point for your task management system, with scalability in mind for future enhancements like authentication or user management.

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *