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 row, show it, and answer 404 when there is none. 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

The template jobs/job_detail.html is ready. Give every job its own page:

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

Press Run, open /jobs/ and click a title.

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