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.
PROJECT 4 · LESSON 8 OF 16
Reuse the task form for updates and require confirmation before deletion.
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.
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.
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.
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.
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.
Read this sequence before the source. Identify the input, the component or function that handles it, and the result the learner sees.
The URL captures an integer primary key.
The view retrieves the existing task or returns 404.
GET renders an instance-bound form or a delete confirmation.
POST validates an edit or performs the confirmed delete.
The redirect displays the resulting database state.
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.
Extend the shared task app with update and confirmation-based deletion.
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})
Capture a task primary key for edit and delete.
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"),
]
Link each visible task to its operations.
{% 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 %}
Make the destructive operation a deliberate POST.
{% 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 %}
Temporarily omit instance=task from the POST edit form and submit a valid change.
A new task is created instead of updating the old one. Restore the instance afterward.
A ModelForm needs object identity to update. A URL parameter alone does not automatically attach the retrieved object to the form.
Never call delete before checking request.method. GET requests must remain safe to revisit.
Likely cause: The POST form was created without instance=task.
Check and correct: Use the same retrieved instance for initial display and bound submission.
Likely cause: Deletion runs on GET.
Check and correct: Render confirmation on GET and move delete into the POST branch.
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.
Both display and submission need the same target object. A missing target should fail consistently before either path continues.
No. It validates the path’s shape. Ownership checks must constrain the database lookup separately.