Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Class-based views


May 14, 2021 Django


Table of contents


Class-based views

The view is callable, it accepts the request and returns a response. N ot only can this be a function, but Django provides examples of classes that can be used as views. T hese allow you to use inheritance and blending to construct views and reuse code. F or tasks, there are some generic views that we'll cover later, but you might want to design your own re-usable view structure to suit your use case. For full details, see the class-based view reference document.


Basic examples

Django provides basic view classes for a variety of applications. A ll views are inherited from the View class, which is responsible for linking views to URLs, HTTP method delegation, and other common features. RedirectView provides HTTP redirection and TemplateView extends the base class so that it also renders the template.

Usage in URLconf

The most direct way to use common views is to create them directly in URLconf. If you change some properties only on a class-based view, you can pass them to as_view () method call itself:

from django.urls import path
from django.views.generic import TemplateView

urlpatterns = [
  path('about/', TemplateView.as_view(template_name="about.html")),
]

Passed to any as_view () overrides the properties set on the class. I n this example, we'll template_name to TemplateView. You can use a similar override pattern, RedirectView, on the url property.

Subsyscize a generic view

A second, more powerful way to use a universal view is to inherit and override properties (such as template_name) or methods (such as get_context_data) from an existing view to provide a new value or method. F or example, consider a view that displays only one template, .html. Django has a common view to do this -- TemplateView so we can classify it and override the template name:

# some_app/views.py
from django.views.generic import TemplateView

class AboutView(TemplateView):
  template_name = "about.html"

Then we need to add this new view to our URLLconf. TemplateView is a class, not a function, so we point the URL to the as_view() class method, which provides function-like entries for class-based views:

# urls.py
from django.urls import path
from some_app.views import AboutView

urlpatterns = [
  path('about/', AboutView.as_view()),
]

For more information on how to use the built-in universal view, refer to the next topic for a universal class-based view.

Other HTTP methods are supported

Suppose someone wants to use views as an API to access our library through HTTP. A pi clients connect from time to time and download book data for books published since the last visit. H owever, if no new books appear since then, getting the books from the database, rendering the full response, and sending it to the client will waste CPU time and bandwidth. It's a good idea to ask the API about the release of the latest books.

We map the URL to the list view of the book in URLLconf:

from django.urls import path
from books.views import BookListView

urlpatterns = [
  path('books/', BookListView.as_view()),
]

And views:

from django.http import HttpResponse
from django.views.generic import ListView
from books.models import Book

class BookListView(ListView):
  model = Book

  def head(self, *args, **kwargs):
      last_book = self.get_queryset().latest('publication_date')
      response = HttpResponse()
      # RFC 1123 date format
      response['Last-Modified'] = last_book.publication_date.strftime('%a, %d %b %Y %H:%M:%S GMT')
      return response

If you request access to the view from gett, the list of objects (using the template) is returned book_list.html response. H owever, if the customer makes a HEAD request, the body of the response is empty and the Last-Modified title indicates the release time of the latest book. Based on this information, clients can download or not download the complete list of objects.

For more information: https://docs.djangoproject.com/en/3.0/