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.
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
:
Python1from rest_framework import generics 2from .models import Todo 3from .serializers import TodoSerializer 4 5class TodoDelete(generics.DestroyAPIView): 6 queryset = Todo.objects.all() 7 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.
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
:
Python1from django.urls import path 2from .views import TodoDelete, TodoUpdate, TodoListCreate, TodoDetail 3 4urlpatterns = [ 5 path('todos/', TodoListCreate.as_view(), name='todo_list_create'), 6 path('todos/delete/<int:pk>/', TodoDelete.as_view(), name='todo_delete'), # New URL 7 path('todos/update/<int:pk>/', TodoUpdate.as_view(), name='todo_update'), 8 path('todos/<int:pk>/', TodoDetail.as_view(), name='todo_detail'), 9]
- We map the URL pattern
/todo/delete/<int:pk>/
to ourTodoDelete
view, where<int:pk>
is a placeholder for the unique identifier of the To-Do item to be deleted. TodoListCreate
andTodoDetail
paths are also included to handle list, create, and detail operations, respectively, they are the same as in the previous lesson.
Here is the code for send_request.py
that shows how to create and delete a To-Do item:
Python1import requests 2 3URL = 'http://127.0.0.1:8000/api/todos/' 4 5# Create a new To-Do item to ensure the database is not empty 6new_todo = {'task': 'Task to delete'} 7post_response = requests.post(URL, json=new_todo) 8print(post_response.json()) # Expect to see the newly created TODO item 9 10# Delete the newly created To-Do item 11todo_id = post_response.json()['id'] 12delete_url = f'{URL}delete/{todo_id}/' 13delete_response = requests.delete(delete_url) 14print(delete_response.status_code) # Expect 204 No Content status code 15 16# Verify deletion by trying to retrieve the deleted To-Do item 17get_response = requests.get(f'{URL}{todo_id}) 18print(get_response.status_code) # Expect 404 Not Found status code
- As in the previous lessons, we first send a POST request to create a new To-Do item. The response will include the details of the created item, including its
id
. - Using the
id
from the created To-Do item, we send a DELETE request to delete it. A successful deletion should return a204 No Content
status code. - Finally, attempting to retrieve the deleted To-Do item should return a
404 Not Found
status code, indicating that the item no longer exists.
In this lesson, we covered the final part of the CRUD operations — deleting a To-Do item. We implemented the TodoDelete
view, updated the URL configuration, and tested the delete functionality using Python's requests
library.
Key points to remember:
- Implementing a delete view using
DestroyAPIView
. - Updating URL configurations to include the delete operation.
- Sending DELETE requests and verifying responses to ensure successful deletion.
Congratulations on completing this lesson and the entire course! You've now built a fully functional To-Do app with Django REST framework that supports creating, retrieving, updating, and deleting To-Do items. Your skills in handling CRUD operations will be invaluable in building more complex applications in the future.
Now, take the upcoming practice exercises to solidify your understanding, and don't hesitate to revisit any part of the course if needed. Happy coding!