Updating a To-Do

Introduction

Welcome to the lesson on updating To-Do items! In this lesson, we will focus on updating existing To-Do items using the Django REST framework. By the end of this lesson, you will be able to create an endpoint that allows users to modify their To-Dos, and you will understand how to test this functionality with HTTP requests.

Imagine a user made a typo when creating a new ToDo in our app and wants to fix it. Updating a resource is a critical part of RESTful architecture, where the PUT method allows you to modify an existing record. In this context, we will build upon the previous lessons where we learned to create and retrieve To-Dos. Let’s dive in!

Recap of Prior Setup

Before we proceed, let's quickly recap the fundamental setup we've done so far. This includes defining our model and serializer for To-Do items. Here’s a brief reminder of what our models.py and serializers.py look like:

myproject/myapp/models.py

from django.db import models

class Todo(models.Model):
    task = models.CharField(max_length=255)
    completed = models.BooleanField(default=False)

    def __str__(self):
        return self.task

myproject/myapp/serializers.py

from rest_framework import serializers
from .models import Todo

class TodoSerializer(serializers.ModelSerializer):
    class Meta:
        model = Todo
        fields = ['id', 'task', 'completed']

With these essential components set up, we're ready to create the update view.

Creating the Update API View

To enable updating To-Do items, we will use the UpdateAPIView class from the Django REST framework. Here’s how you can create the Update view:

myproject/myapp/views.py

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

class TodoUpdate(generics.UpdateAPIView):
    queryset = Todo.objects.all()
    serializer_class = TodoSerializer

Explanation:

  • We import generics from rest_framework.
  • We define a class TodoUpdate that inherits from generics.UpdateAPIView.
  • We set queryset to Todo.objects.all(), which retrieves all To-Do items from the database.
  • We assign TodoSerializer to serializer_class to determine the structure of our data.

This view will handle PUT and PATCH requests to update an existing To-Do item. As you can see, creating it is straightforward and very similar to other generics we tried. However, again, it is vital to understand the details of how it is used.

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