Skip to lesson content

PROJECT 4 · LESSON 8 OF 16

Finish CRUD with edit, completion and deletion

Reuse the task form for updates and require confirmation before deletion.

  • instance
  • primary keys
  • POST-only writes
  • 404

Your workspace: edushop

Continue from lesson 7: Create a persistent task application. Keep existing files; create or replace the complete files listed below.

Extract the ZIP and open the folder containing manage.py. Create a Python virtual environment, install requirements.txt and run migrate. Read README.md for checkpoint-specific commands and LESSON.md for offline explanations. Checkpoints contain no database records or private credentials.

1. Understand the problem and the concepts

Why we need this feature

A useful task application must change and remove existing records. These operations teach the difference between creating a new object and editing a particular one, and why a clickable link should never delete data immediately.

Editing uses the same form class but binds it to an existing instance. Without instance, a valid form would create another record instead of updating the selected one.

GET /tasks/1/delete/ displays a confirmation page. Only its CSRF-protected POST actually deletes. A link should never mutate data by being visited or prefetched.

Editing requires the existing instance

The edit URL carries a primary key. get_object_or_404 retrieves that task or ends with 404. Pass instance=task to TaskForm for both GET and POST. On GET this fills the inputs; on POST it tells save which row to update. Without instance, a valid form creates a new task instead of editing the selected one.

A checkbox submits a value when checked and normally submits nothing when unchecked. Django’s BooleanField handling interprets that correctly. Do not manually treat the presence of any arbitrary string as proof of a true business value; let the form convert its declared fields.

A confirmation page is a read; deletion is a write

GET delete displays the task and a confirmation form. POST delete performs task.delete and redirects. This permits a visitor to cancel without side effects. It also prevents link previews and ordinary navigation from destroying records. Keep csrf_token in the confirmation form.

A deleted task cannot be edited later using an old URL; get_object_or_404 handles that normal stale-link case. Returning 404 is better than an unhandled DoesNotExist exception. The task list should also handle zero remaining tasks with a useful empty state.

Trace the complete state transition

Think in before-and-after states. Before an edit, the database row has title A and completed=False. A valid POST with title B and a checked completion field updates that same row to B and True. Invalid input leaves the original row unchanged. A delete POST removes it.

At this stage the primary key selects a shared local record. It is not an authorization mechanism. Sequential IDs are easy to guess. The later private-task project must add owner filtering to every lookup, not merely hide edit links in the page.

2. Follow the execution flow

Read this sequence before the source. Identify the input, the component or function that handles it, and the result the learner sees.

  1. The URL captures an integer primary key.

  2. The view retrieves the existing task or returns 404.

  3. GET renders an instance-bound form or a delete confirmation.

  4. POST validates an edit or performs the confirmed delete.

  5. The redirect displays the resulting database state.

Prove update is not create

  1. Create one task and note the number of tasks.
  2. Edit its title and mark it complete. The count stays constant.
  3. Open delete confirmation and cancel: the row remains. Submit confirmation: the row disappears.

3. Build it, one file at a time

  1. Replace the task views and routes and add edit/delete links.
  2. Edit a title, check Completed, save, and compare the stored ID before and after.
  3. Visit a delete-confirmation URL and cancel. Then submit the form and verify the task is gone.

The paths below are relative to your practice project. Each block is the complete file at this checkpoint. Read its responsibility first, type or copy the code, then use the walkthrough to explain the important statements.

tasks/views.py

Extend the shared task app with update and confirmation-based deletion.

tasks/views.py
from django.contrib import messages
from django.shortcuts import render, redirect, get_object_or_404
from .forms import TaskForm
from .models import Task


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


def task_create(request):
    form = TaskForm(request.POST if request.method == "POST" else None)
    if request.method == "POST" and form.is_valid():
        form.save()
        messages.success(request, "Task created.")
        return redirect("tasks:list")
    return render(request, "tasks/form.html", {"form": form, "heading": "Create task"})


def task_edit(request, pk):
    task = get_object_or_404(Task, pk=pk)
    form = TaskForm(request.POST if request.method == "POST" else None, instance=task)
    if request.method == "POST" and form.is_valid():
        form.save()
        messages.success(request, "Task updated.")
        return redirect("tasks:list")
    return render(request, "tasks/form.html", {"form": form, "heading": "Edit task"})


def task_delete(request, pk):
    task = get_object_or_404(Task, pk=pk)
    if request.method == "POST":
        task.delete()
        messages.success(request, "Task deleted.")
        return redirect("tasks:list")
    return render(request, "tasks/confirm_delete.html", {"task": task})

Read the code

  1. get_object_or_404 validates the target record exists before the form uses it.
  2. instance=task tells ModelForm to update that row. GET builds initial values; invalid POST retains submitted values and errors.
  3. Deletion occurs only inside the POST branch. The GET branch renders a confirmation and leaves the record unchanged.

tasks/urls.py

Capture a task primary key for edit and delete.

tasks/urls.py
from django.urls import path
from . import views

app_name = "tasks"
urlpatterns = [
    path("", views.task_list, name="list"),
    path("<int:pk>/edit/", views.task_edit, name="edit"),
    path("<int:pk>/delete/", views.task_delete, name="delete"),
    path("new/", views.task_create, name="create"),
]

Read the code

  1. The int converter passes an integer as pk. It validates the path shape, not record existence or ownership.

templates/tasks/list.html

Link each visible task to its operations.

templates/tasks/list.html
{% extends "base.html" %}
{% block content %}<h1>Tasks</h1><a href="{% url 'tasks:create' %}">Create task</a>
{% for task in tasks %}<article><h2>{{ task.title }}</h2><p>{{ task.completed|yesno:"Completed,Open" }}</p><a href="{% url 'tasks:edit' task.pk %}">Edit</a> <a href="{% url 'tasks:delete' task.pk %}">Delete</a></article>{% empty %}<p>No tasks yet.</p>{% endfor %}{% endblock %}

Read the code

  1. Named routes reverse with task.pk. Hiding a link is presentation, not access control; ownership checks are added in Project 5.

templates/tasks/confirm_delete.html

Make the destructive operation a deliberate POST.

templates/tasks/confirm_delete.html
{% extends "base.html" %}
{% block content %}<h1>Delete task?</h1><p>{{ task.title }}</p><form method="post">{% csrf_token %}<button>Confirm deletion</button></form><a href="{% url 'tasks:list' %}">Cancel</a>{% endblock %}

Read the code

  1. The page presents the current task title and a cancel link. csrf_token is required just as it is for create and edit.

4. Run it and check your result

  • Editing changes the existing record and does not add a duplicate.
  • GET deletion leaves the record intact; confirmation POST removes it.
  • Unknown task IDs return 404.

5. Predict, change and observe

Temporarily omit instance=task from the POST edit form and submit a valid change.

Compare your prediction with the expected result

What you should observe

A new task is created instead of updating the old one. Restore the instance afterward.

Why it happens

A ModelForm needs object identity to update. A URL parameter alone does not automatically attach the retrieved object to the form.

6. Troubleshoot with evidence

A common mistake

Never call delete before checking request.method. GET requests must remain safe to revisit.

Editing duplicates tasks

Likely cause: The POST form was created without instance=task.

Check and correct: Use the same retrieved instance for initial display and bound submission.

Clicking a link deletes immediately

Likely cause: Deletion runs on GET.

Check and correct: Render confirmation on GET and move delete into the POST branch.

7. Practice and explain it back

Your independent task

Add a completed/open filter to the list with a GET query parameter.

Attempt these questions before opening the explanations. Use the source above to justify your answer.

Why retrieve before checking the method?

Both display and submission need the same target object. A missing target should fail consistently before either path continues.

Does an integer ID protect a record?

No. It validates the path’s shape. Ownership checks must constrain the database lookup separately.