Adding to the Context
Part of the Class-Based Views section of Coddy's Django journey. Lesson 3 of 18.
The home page could be a TemplateView too, except that its template needs data. The variables a template receives are its context, and a generic view builds them in a method, get_context_data(). Override it to add your own. A recipe site counts its quick recipes:
class RecipeHomeView(TemplateView):
template_name = "recipes/home.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["quick"] = Recipe.objects.filter(minutes__lte=30).count()
return contextThree steps, always the same: super().get_context_data(**kwargs) gets the dictionary Django built, you add your keys, and you return the dictionary. The template gets whatever this method returns.
The query sits inside the method, so it runs on every request. As a class attribute it would run once, when the server starts, and the number would never change.
Challenge
EasyThe home template now also shows the newest job. Rewrite HomeView:
- A
TemplateViewforjobs/home.html, with noget(). - It adds
count, the number of jobs, andlatest, the job with the newestposteddate, to the context.
Press Run: the home page says 12 jobs open and Newest: Python Developer at Brightline.
Try it yourself
from django.shortcuts import render
from django.views import View
from django.views.generic import TemplateView
from .models import Job
class HomeView(View):
def get(self, request):
count = Job.objects.count()
return render(request, "jobs/home.html", {"count": count})
class AboutView(TemplateView):
template_name = "jobs/about.html"
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