Menu
CoddyTech

Deleting a Task

Part of the JSON APIs section of Coddy's Django journey. Lesson 10 of 19.

A finished task should be gone, not only ticked: DELETE /api/tasks/1/ removes task 1, and then there is nothing to send back.

For that HTTP has 204 No Content: the request worked and the answer has no body. A JsonResponse always writes a body, even {}. A plain HttpResponse with only a status sends nothing else:

return HttpResponse(status=204)

Keep the 404 check first, so deleting a missing task still answers 404.

One URL, three methods: GET reads the task, PATCH changes it, DELETE removes it. A URL per resource, with the method as the verb, is what people call a REST API.

challenge icon

Challenge

Easy

Let programs delete a task with DELETE /api/tasks/<id>/:

  • Allow "DELETE" on task_detail.
  • Delete the task and answer 204 with an empty body.
  • A missing task still answers 404.

Press Run, then in the Shell tab: from django.test import Client; print(Client().delete("/api/tasks/1/").status_code) prints 204.

Try it yourself

import json

from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_GET, require_http_methods

from .models import Task


def task_to_dict(task):
    return {
        "id": task.id,
        "title": task.title,
        "done": task.done,
        "priority": task.priority,
    }


def home(request):
    return render(request, "tasks/home.html", {"tasks": Task.objects.all()})


@require_GET
def stats(request):
    data = {
        "total": Task.objects.count(),
        "done": Task.objects.filter(done=True).count(),
    }
    return JsonResponse(data)


@csrf_exempt
@require_http_methods(["GET", "POST"])
def task_list(request):
    if request.method == "POST":
        try:
            data = json.loads(request.body)
        except json.JSONDecodeError:
            return JsonResponse({"error": "The body is not valid JSON."}, status=400)
        errors = {}
        title = data.get("title", "").strip()
        if not title:
            errors["title"] = "This field is required."
        if errors:
            return JsonResponse({"errors": errors}, status=400)
        task = Task.objects.create(
            title=title,
            priority=data.get("priority", "normal"),
        )
        return JsonResponse(task_to_dict(task), status=201)
    tasks = Task.objects.all()
    done = request.GET.get("done")
    if done == "true":
        tasks = tasks.filter(done=True)
    elif done == "false":
        tasks = tasks.filter(done=False)
    return JsonResponse([task_to_dict(task) for task in tasks], safe=False)


@csrf_exempt
@require_http_methods(["GET", "PATCH"])
def task_detail(request, pk):
    task = Task.objects.filter(pk=pk).first()
    if task is None:
        return JsonResponse({"error": "Task not found"}, status=404)
    if request.method == "PATCH":
        data = json.loads(request.body)
        if "title" in data:
            task.title = data["title"]
        if "done" in data:
            task.done = data["done"]
        task.save()
    return JsonResponse(task_to_dict(task))

All lessons in JSON APIs

Practice on your own: Django playground