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 firstWith no template_name, it renders recipes/recipe_list.html: the app label, the model's name in lowercase, then _list.html. The rows arrive as object_list and recipe_list, or under the name in context_object_name.
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
EasyAdd the jobs page. Its template, jobs/job_list.html, is ready and loops over jobs.
- In
jobs/views.py, aJobListView, aListViewofJob, with the list namedjobsand the newestposteddate first. Keep the default template. - In
jobs/urls.py, a route"jobs/"namedlist.
Press Run and open /jobs/.
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