Deleting a To-Do

Introduction

Welcome to our final lesson in the "Implementing API for TODO App with Django" course. Today, we will be focusing on the Delete operation, the last part of the CRUD (Create, Read, Update, Delete) setup. Deleting a To-Do item is crucial for maintaining the relevance and accuracy of our To-Do list. For instance, once you complete a task in a To-Do list, you want to remove it from the list to keep things clean and focused on what remains to be done.

Creating the Delete API View

To delete a To-Do item, we need to create a view that handles the delete operation. Django REST framework provides a generic view class called DestroyAPIView, which we can utilize to implement this functionality.

Here is the code to create the TodoDelete view in views.py:

from rest_framework import generics
from .models import Todo
from .serializers import TodoSerializer

class TodoDelete(generics.DestroyAPIView):
    queryset = Todo.objects.all()
    serializer_class = TodoSerializer
  • DestroyAPIView: This is a generic class provided by Django REST framework that supports the HTTP DELETE method, which is used to delete a resource.
  • queryset: This defines the list of To-Do items from which the delete operation will retrieve the item to be deleted.
  • serializer_class: This defines the serializer linked to the model, ensuring the correct serialization and validation of data.

Updating URL Configuration

Now that we have our delete view, we need to update the URL configuration to make this view accessible. Let's define the URL path for the delete operation in urls.py:

from django.urls import path
from .views import TodoDelete, TodoUpdate, TodoListCreate, TodoDetail

urlpatterns = [
    path('todos/', TodoListCreate.as_view(), name='todo_list_create'),
    path('todos/delete/<int:pk>/', TodoDelete.as_view(), name='todo_delete'),   # New URL
    path('todos/update/<int:pk>/', TodoUpdate.as_view(), name='todo_update'),
    path('todos/<int:pk>/', TodoDetail.as_view(), name='todo_detail'),
]
  • We map the URL pattern /todo/delete/<int:pk>/ to our TodoDelete view, where <int:pk> is a placeholder for the unique identifier of the To-Do item to be deleted.
  • TodoListCreate and TodoDetail paths are also included to handle list, create, and detail operations, respectively, they are the same as in the previous lesson.
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal