Skip to lesson content

PROJECT 5 · LESSON 10 OF 16

Make tasks private and test access rules

Restrict lists, edits and deletion to the current authenticated owner.

  • login_required
  • ownership
  • commit=False
  • authorization

Your workspace: edushop

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.

1. Understand the problem and the concepts

Why we need this feature

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.

Require identity before handling a private feature

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.

Scope every object lookup to its owner

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.

Existing shared records need an explicit policy

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.

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. Authentication middleware identifies the current user.

  2. login_required rejects anonymous access before the private view proceeds.

  3. The query includes the authenticated owner.

  4. Only an owned object reaches edit or delete logic.

  5. The response or redirect reveals only that user’s data.

Run the two-account privacy check

  1. Create Alice and Bob with separate browser sessions.
  2. As Alice, create a task and copy its edit and delete URLs.
  3. As Bob, open both URLs and attempt submissions. Expect 404 and confirm Alice’s task is unchanged.

3. Build it, one file at a time

  1. Replace the task views with the protected version. No new migration is needed because owner was included earlier.
  2. Create one task as user A and another as user B in isolated browser sessions. Verify their lists differ.
  3. Copy A’s edit URL into B’s browser and try both GET and POST. Both must be rejected without changing A’s record.

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

Enforce identity and ownership on each task operation.

tasks/views.py
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})

Read the code

  1. login_required redirects signed-out requests before the view runs. It does not by itself decide which task an authenticated user owns.
  2. The list query includes owner=request.user. Detail lookups combine pk and owner, so foreign-owned IDs behave like missing records.
  3. On create, save(commit=False) constructs the unsaved model, then the server sets owner before save. The caller cannot choose another owner through the form.

4. Run it and check your result

  • Signed-out task visits redirect to login.
  • A and B see only their own records; B cannot edit or delete A’s task by changing the URL.

5. Predict, change and observe

Post an extra owner field while creating a task as Bob.

Compare your prediction with the expected result

What you should observe

The created task still belongs to Bob.

Why it happens

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.

6. Troubleshoot with evidence

A common mistake

Do not filter private rows after sending them to a template or browser. Constrain the database query before rendering.

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.

A second user can edit a copied URL

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.

7. Practice and explain it back

Your independent task

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.

Why return 404 for someone else’s task?

The task is outside the current user’s accessible collection. A consistent 404 avoids revealing whether that guessed ID belongs to another user.

Is login_required enough?

It verifies identity, not ownership. Object-level query restrictions decide which records that identity may access.