Skip to main content
← Python backend foundationsStep 9 of 11

Backend Development

Build a Django Task Tracker, Part 2: Forms, Login and Ownership

Build a private task list with validated forms, owner-scoped queries, and CSRF-protected completion.

A task tracker becomes useful when a person can add a task and see their own list. This chapter connects HTTP requests, authentication, form validation, and ownership. Continue in the project downloaded in part one; the files shown here are already included in that finished example.

Before starting, run the migrations and create a local account. Start the development server, open /accounts/login/, and sign in. Django's built-in authentication URLs provide the login/logout views; our templates/registration/login.html provides the login form. Public registration is outside this small project.

Expose only the fields a reader may edit

A browser can send fields that do not appear in your HTML. The form must define the allowed input:

tasks/forms.py

from django import forms
from .models import Task


class TaskForm(forms.ModelForm):
    class Meta:
        model = Task
        fields = ['title']

Only title is editable. A client cannot use this form to choose another owner or create an already-completed task. ModelForm derives the title's maximum length from the model and treats blank input as invalid. Its text field strips surrounding whitespace, so a title containing only spaces also fails validation.

This field list is a useful security boundary. Avoid fields = '__all__' for a model that includes ownership or administrative flags. Adding a model field later should not silently make it writable from a public form.

Follow a request through the views

The list and completion views share the same owner boundary:

tasks/views.py

from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator
from django.db.models import F
from django.shortcuts import get_object_or_404, redirect, render
from django.views.decorators.http import require_POST, require_http_methods
from .forms import TaskForm
from .models import Task


@login_required
@require_http_methods(["GET", "POST"])
def task_list(request):
    form = TaskForm()
    if request.method == 'POST':
        form = TaskForm(request.POST)
        if form.is_valid():
            task = form.save(commit=False)
            task.owner = request.user
            task.save()
            return redirect('tasks:list')
    tasks = Task.objects.filter(owner=request.user)
    page = Paginator(tasks, 20).get_page(request.GET.get('page'))
    return render(request, 'tasks/list.html', {'form': form, 'page_obj': page})


@login_required
@require_POST
def toggle_task(request, pk):
    task = get_object_or_404(Task, pk=pk, owner=request.user)
    Task.objects.filter(pk=task.pk, owner=request.user).update(completed=~F('completed'))
    return redirect('tasks:list')

For a GET, the page receives an unbound form. For a POST, the submitted data is bound and validated. The explicit TaskForm(request.POST) inside the POST branch matters: even an empty POST must be a bound, invalid form rather than an apparently untouched form.

save(commit=False) creates an unsaved model instance. We assign request.user on the server before saving. Values such as owner=42 or completed=true in a forged request do not appear in the form's allowed fields and do not control those model attributes.

After a successful save, the view redirects to the list. Refreshing that GET does not repeat the previous creation request. An invalid form is rendered again with its errors and the existing user's list, allowing a correction without losing feedback.

Scope reads as carefully as writes

Task.objects.filter(owner=request.user) is the list's privacy boundary. A login requirement tells us who made the request; the owner filter determines which records that person may see. Neither replaces the other.

The toggle lookup combines the requested primary key with the current owner. Someone guessing another task ID receives a 404 instead of modifying that task. A missing and a foreign record are handled in the same way. The update repeats the ownership filter and flips the stored boolean with a database expression, avoiding a read/modify/write inversion in Python. This is a toggle operation: two accepted requests toggle twice, so it is not an idempotent “set complete” API.

require_POST prevents changing state through a GET link. POST alone does not prevent forgery; the template supplies CSRF tokens and Django's middleware validates them. The login requirement also applies to both views.

Connect the URL and template

tasks/urls.py

from django.urls import path
from . import views
app_name = 'tasks'
urlpatterns = [path('', views.task_list, name='list'), path('<int:pk>/toggle/', views.toggle_task, name='toggle')]

The root configuration includes these URLs alongside /accounts/ and /admin/. Namespaced names such as tasks:list keep redirects and templates independent of literal URL strings.

templates/tasks/list.html

{% extends 'base.html' %}
{% block content %}
<h2>Your tasks</h2><form method="post">{% csrf_token %}{{ form.as_p }}<button>Add task</button></form>
<ul>{% for task in page_obj %}<li><span {% if task.completed %}class="complete"{% endif %}>{{ task.title }}</span> <form class="inline" method="post" action="{% url 'tasks:toggle' task.pk %}">{% csrf_token %}<button>{% if task.completed %}Mark incomplete{% else %}Complete{% endif %}</button></form></li>{% empty %}<li>No tasks yet. Add your first task above.</li>{% endfor %}</ul>
<nav aria-label="Task pages">{% if page_obj.has_previous %}<a href="?page={{ page_obj.previous_page_number }}">Previous</a>{% endif %}<span>Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}</span>{% if page_obj.has_next %}<a href="?page={{ page_obj.next_page_number }}">Next</a>{% endif %}</nav>
{% endblock %}

Every state-changing form contains {% csrf_token %}. Titles use normal template autoescaping. Do not add the safe filter to user-entered titles: a task named <script>...</script> should display as text, not run code.

The paginator limits the list to 20 tasks per page and uses the model ordering. It operates after owner filtering, so the count and page boundaries belong to that user. An empty list shows a useful next action instead of an empty panel. Changing completion returns to the first page in this version; preserving the current page is a reasonable later enhancement.

Verify it with two accounts

Create an ordinary second user through admin and sign into a separate browser profile. Add tasks for both users. Confirm that each list contains only its owner's tasks, then request another user's toggle URL. It should not work. Opening your own toggle URL as a normal browser link should return 405 because the browser used GET.

Try a blank title, 161 characters, and a title containing HTML. Write down the expected behavior before testing. In part three, we encode these checks so future edits cannot quietly remove them.

References: Django's authentication guide, model forms, and CSRF guide.

Step 9 of 11 · Python backend foundations

Put this step into practice.

Use two accounts to verify task privacy, then test invalid form input.

Enable JavaScript to save progress. You can still continue through the path.

Stay curious

A new idea for your inbox.

Occasional updates when we publish new guides. No noise.

Subscribing...