Class-based views
In Chapter 1 and at the start of
this chapter -- in listing 2-1 -- you saw how to define a Django
url and make it operate with a Django template without the need of
a view method. This was possible due to the
django.views.generic.TemplateView
class, which is
called a class-based view.
Unlike Django view methods backed
by standard Python methods that use a Django
HttpRequest
input parameter and output a Django
HttpResponse
, class-based views offer their
functionality through full-fledged Python classes. This in turn
allows Django views to operate with object oriented programming
(OOP) principles (e.g. encapsulation, polymorphism and inheritance)
leading to greater re-usability and shorter implementation
times.
Although Django class-based views represent a more powerful approach to create Django views, they are simply an alternative to the view methods you've used up to this point. If you want to quickly execute business logic on Django requests you can keep using view methods, but for more demanding view requirements (e.g. form processing, boilerplate model queries) class-based views can save you considerable time.
Built-in class-based views
The functionality provided by the
django.views.generic.TemplateView
class-based view is
real a time saver. While it would have been possible to configure a
url to execute on an empty view method and then send control to a
template, the TemplateView
class allows this process
to be done in one line.
In addition to the
TemplateView
class-based view, Django offers many
other built-in class-based views to shorten the creation process
for common Django view operations using OOP-like principles. Table
2-11 illustrates Django's built-in classes for views.
Table 2-11. Built-in classes for views
Class | Description |
---|---|
django.views.generic.View |
Parent class of all class-based views, providing core functionality. |
django.views.generic.TemplateView |
Allows a url to return the contents of a template, without the need of a view. |
django.views.generic.RedirectView |
Allows a url to perform a redirect, without the need of a view. |
django.views.generic.ArchiveIndexView |
Allows a view to return date-based object results, without the need to explicitly perform Django model queries. |
django.views.generic.CreateView |
Allows a view to execute Create-Read-Update-Delete (CRUD) operations , without the need to explicitly perform Django model queries. |
In the upcoming and final section of this chapter, I'll explain the
classes in the top-half of table 2-11 so you can gain a better
understanding of the structure and execution process of Django
class-based views. The class-based views in bottom half of table
2-11 that involve Django models are described in a separate chapter
on Django class-based views models.
The remaining content for Django 4.0 is only available with a subscription.