Old tasks disappeared
Likely cause: Their owner is NULL from the shared local stage.
Check and correct: Inspect the database deliberately; new private queries are correctly excluding unowned records.
PROJECT 5 · LESSON 10 OF 16
Restrict lists, edits and deletion to the current authenticated owner.
Continue from lesson 9: Add registration, login and logout. 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 private task manager must enforce ownership even when someone manually changes a URL or submits a forged form. This lesson moves access rules into server-side queries so privacy does not depend on the interface.
A login page alone does not protect records. Apply the user filter in every data operation, including direct requests to edit and delete.
Tasks created in Project 4 have owner=NULL and intentionally become invisible. Do not claim all old rows for the first person who signs in.
login_required redirects anonymous visitors to login, usually including the intended destination in next. Once authenticated, the view can use request.user as a trusted identity supplied by Django’s authentication layer. A posted username or owner ID is not equivalent; visitors control those values.
Apply login_required to list, create, edit and delete. Protecting only the list leaves direct mutation URLs exposed. Protecting only the navigation hides buttons but changes nothing about what the server accepts. Always test the direct URL, including POST.
Task.objects.filter(owner=request.user) limits the list. get_object_or_404(Task, pk=pk, owner=request.user) limits an individual edit or delete. Both the primary key and owner condition must match. Another user’s task produces 404 through the same path as a missing task, without disclosing its contents.
For creation, call form.save(commit=False), set task.owner=request.user, then save. The form whitelist excludes owner. A visitor posting an extra owner field cannot choose someone else because the view supplies the value. ModelForm validation does not automatically infer this authorization rule.
Earlier tasks have owner=NULL. The private queries intentionally hide them from everyone. Do not assign them to whichever user happens to log in next. For a disposable tutorial you may delete those lab rows in a shell after inspecting them; a real migration needs a verified ownership mapping or another documented policy.
A private window lets you test Alice and Bob separately. Create as Alice, copy the edit address and open it as Bob. Then attempt a direct POST as Bob. The database record must remain unchanged. The regression tests added later automate these cases so future refactoring cannot silently remove the protection.
Read this sequence before the source. Identify the input, the component or function that handles it, and the result the learner sees.
Authentication middleware identifies the current user.
login_required rejects anonymous access before the private view proceeds.
The query includes the authenticated owner.
Only an owned object reaches edit or delete logic.
The response or redirect reveals only that user’s data.
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.
Enforce identity and ownership on each task operation.
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.shortcuts import render, redirect, get_object_or_404
from .forms import TaskForm
from .models import Task
@login_required
def task_list(request):
return render(request, "tasks/list.html", {"tasks": Task.objects.filter(owner=request.user)})
@login_required
def task_create(request):
form = TaskForm(request.POST if request.method == "POST" else None)
if request.method == "POST" and form.is_valid():
task = form.save(commit=False)
task.owner = request.user
task.save()
messages.success(request, "Task created.")
return redirect("tasks:list")
return render(request, "tasks/form.html", {"form": form, "heading": "Create task"})
@login_required
def task_edit(request, pk):
task = get_object_or_404(Task, pk=pk, owner=request.user)
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"})
@login_required
def task_delete(request, pk):
task = get_object_or_404(Task, pk=pk, owner=request.user)
if request.method == "POST":
task.delete()
messages.success(request, "Task deleted.")
return redirect("tasks:list")
return render(request, "tasks/confirm_delete.html", {"task": task})
Post an extra owner field while creating a task as Bob.
The created task still belongs to Bob.
The form only accepts declared editable fields, and the view assigns the owner from request.user. Hidden HTML fields are never a trusted identity source.
Do not filter private rows after sending them to a template or browser. Constrain the database query before rendering.
Likely cause: Their owner is NULL from the shared local stage.
Check and correct: Inspect the database deliberately; new private queries are correctly excluding unowned records.
Likely cause: The detail lookup checks only pk.
Check and correct: Add owner=request.user to every edit and delete lookup, then rerun direct GET and POST checks.
Add task due dates while preserving owner filtering in every query.
Attempt these questions before opening the explanations. Use the source above to justify your answer.
The task is outside the current user’s accessible collection. A consistent 404 avoids revealing whether that guessed ID belongs to another user.
It verifies identity, not ownership. Object-level query restrictions decide which records that identity may access.