Class-based views

A view is a callable which takes a request and returns aresponse. This can be more than just a function, and Django providesan example of some classes which can be used as views. These allow youto structure your views and reuse code by harnessing inheritance andmixins. There are also some generic views for tasks which we’ll get to later,but you may want to design your own structure of reusable views which suitsyour use case. For full details, see the class-based views referencedocumentation.

Basic examples

Django provides base view classes which will suit a wide range of applications.All views inherit from the View class, whichhandles linking the view in to the URLs, HTTP method dispatching and othercommon features. RedirectView provides aHTTP redirect, and TemplateView extends thebase class to make it also render a template.

Usage in your URLconf

The most direct way to use generic views is to create them directly in yourURLconf. If you’re only changing a few attributes on a class-based view, youcan pass them into the as_view() methodcall itself:

  1. from django.urls import path
  2. from django.views.generic import TemplateView
  3.  
  4. urlpatterns = [
  5. path('about/', TemplateView.as_view(template_name="about.html")),
  6. ]

Any arguments passed to as_view() willoverride attributes set on the class. In this example, we set template_nameon the TemplateView. A similar overriding pattern can be used for theurl attribute on RedirectView.

Subclassing generic views

The second, more powerful way to use generic views is to inherit from anexisting view and override attributes (such as the template_name) ormethods (such as get_context_data) in your subclass to provide new valuesor methods. Consider, for example, a view that just displays one template,about.html. Django has a generic view to do this -TemplateView - so we can subclass it, andoverride the template name:

  1. # some_app/views.py
  2. from django.views.generic import TemplateView
  3.  
  4. class AboutView(TemplateView):
  5. template_name = "about.html"

Then we need to add this new view into our URLconf.TemplateView is a class, not a function, sowe point the URL to the as_view() classmethod instead, which provides a function-like entry to class-based views:

  1. # urls.py
  2. from django.urls import path
  3. from some_app.views import AboutView
  4.  
  5. urlpatterns = [
  6. path('about/', AboutView.as_view()),
  7. ]

For more information on how to use the built in generic views, consult the nexttopic on generic class-based views.

Supporting other HTTP methods

Suppose somebody wants to access our book library over HTTP using the viewsas an API. The API client would connect every now and then and download bookdata for the books published since last visit. But if no new books appearedsince then, it is a waste of CPU time and bandwidth to fetch the books from thedatabase, render a full response and send it to the client. It might bepreferable to ask the API when the most recent book was published.

We map the URL to book list view in the URLconf:

  1. from django.urls import path
  2. from books.views import BookListView
  3.  
  4. urlpatterns = [
  5. path('books/', BookListView.as_view()),
  6. ]

And the view:

  1. from django.http import HttpResponse
  2. from django.views.generic import ListView
  3. from books.models import Book
  4.  
  5. class BookListView(ListView):
  6. model = Book
  7.  
  8. def head(self, *args, **kwargs):
  9. last_book = self.get_queryset().latest('publication_date')
  10. response = HttpResponse()
  11. # RFC 1123 date format
  12. response['Last-Modified'] = last_book.publication_date.strftime('%a, %d %b %Y %H:%M:%S GMT')
  13. return response

If the view is accessed from a GET request, an object list is returned inthe response (using the book_list.html template). But if the client issuesa HEAD request, the response has an empty body and the Last-Modifiedheader indicates when the most recent book was published. Based on thisinformation, the client may or may not download the full object list.