TemplateView
Part of the Class-Based Views section of Coddy's Django journey. Lesson 2 of 18.
The job board needs an About page that only renders a template. Django has a class for that, TemplateView. Its get() is already written: it renders the template named in template_name. A recipe site keeps its FAQ in recipes/templates/recipes/pages/faq.html:
from django.views.generic import TemplateView
class FaqView(TemplateView):
template_name = "recipes/pages/faq.html"That is the whole view. Django calls its ready-made view classes generic views. You set one up with class attributes such as template_name, and the code Django wrote reads them.
template_name is the name you would pass to render(): the file's path after templates/. Leave out a folder and the page fails with TemplateDoesNotExist. The route is like any class-based view: path("faq/", views.FaqView.as_view(), name="faq").
Challenge
EasyShow the ready template jobs/templates/jobs/about.html at /about/.
- In
jobs/views.py, addAboutView, aTemplateViewthat renders it. - In
jobs/urls.py, add the route"about/"namedabout.
Open /about/: it says Job Board lists jobs at small tech companies in Berlin, Lisbon and London.
Try it yourself
from django.shortcuts import render
from django.views import View
from .models import Job
class HomeView(View):
def get(self, request):
count = Job.objects.count()
return render(request, "jobs/home.html", {"count": count})
All lessons in Class-Based Views
Practice on your own: Django playground