Menu
CoddyTech

DetailView

Part of the Class-Based Views section of Coddy's Django journey. Lesson 5 of 18.

Each job needs a page of its own: find the job, show it, and respond with 404 Page not found when there is no such job. That is DetailView. On a recipe site:

class RecipeDetailView(DetailView):
    model = Recipe


# urls.py
path("recipes/<int:pk>/", views.RecipeDetailView.as_view(), name="recipe")

A DetailView reads the row's primary key from the URL argument named pk and looks the row up the way get_object_or_404() does. Its template defaults to recipes/recipe_detail.html, and the row arrives as object and as recipe.

The name pk matters. A route written <int:id> gives the view an argument it does not look for, and the page crashes with an AttributeError asking for an object pk or a slug.

A link passes the row's pk to the route's name: {% url 'recipes:recipe' recipe.pk %}.

challenge icon

Challenge

Easy

Give every job its own page, with the ready template jobs/job_detail.html.

  1. In jobs/views.py, add JobDetailView, a DetailView of Job.
  2. In jobs/urls.py, add the route "jobs/<int:pk>/" named detail.
  3. In job_list.html, make each job's title a link to its page.

Click Python Developer to open its page, then open /jobs/999/: you see 404 Page not found.

Try it yourself

from django.views.generic import ListView, TemplateView

from .models import Job


class HomeView(TemplateView):
    template_name = "jobs/home.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["count"] = Job.objects.count()
        context["latest"] = Job.objects.order_by("-posted").first()
        return context


class AboutView(TemplateView):
    template_name = "jobs/about.html"


class JobListView(ListView):
    model = Job
    context_object_name = "jobs"
    ordering = ["-posted"]
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Class-Based Views

Practice on your own: Django playground