A View Class
Part of the Class-Based Views section of Coddy's Django journey. Lesson 1 of 18.
This section builds a job board, and its home page is a function view like every view so far. Django also lets you write a view as a class: you subclass View and add one method per HTTP method. A GET request calls get(), a POST calls post().
from django.views import View
class RecipeCountView(View):
def get(self, request):
total = Recipe.objects.count()
return HttpResponse(f"{total} recipes")The method takes self, then request, and returns a response, as a function view does. A route needs a function, and .as_view() makes one from the class: path("count/", views.RecipeCountView.as_view()). On every request that function makes a new object of the class and calls the method that matches.
A method the class does not define, like POST here, gets 405 Method Not Allowed. The payoff comes next: Django ships classes that already do the common jobs.
Challenge
EasyTurn the home page into a class:
- In
jobs/views.py, replace the functionhomewithHomeView, aViewwhoseget()does whathomedid. - In
jobs/urls.py, point the route""at the class. Keepname="home".
Press Run: the home page still says 12 jobs open.
Try it yourself
from django.shortcuts import render
from .models import Job
def home(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