Menu
CoddyTech

ListView

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

The board needs a page that lists every job. A list of a table's rows is so common that Django wrote the view: ListView. Give it a model, and it queries the rows and renders a template with them. A recipe site's list, in the app recipes:

from django.views.generic import ListView


class RecipeListView(ListView):
    model = Recipe
    context_object_name = "recipes"   # {% for recipe in recipes %}
    ordering = ["minutes"]             # quickest first

With no template_name, it renders recipes/recipe_list.html: the app label, the model's name in lowercase, then _list.html. The template always gets the rows as object_list. It also gets them as recipe_list, or, when you set context_object_name, under that name instead.

ordering takes what order_by() takes, so ["-minutes"] would put the slowest recipe first. Without it the rows come in the database's order.

challenge icon

Challenge

Easy

Add the jobs page, with the ready template jobs/job_list.html, which loops over jobs.

  1. In jobs/views.py, add JobListView, a ListView of Job. Name its list jobs, put the newest posted date first and keep the default template.
  2. In jobs/urls.py, add the route "jobs/" named list.

Open /jobs/: Python Developer is first and Technical Writer is last.

Try it yourself

from django.views.generic import 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"

All lessons in Class-Based Views

Practice on your own: Django playground