1. =================
    
  2. Class-based views
    
  3. =================
    
  4. 
    
  5. A view is a callable which takes a request and returns a
    
  6. response. This can be more than just a function, and Django provides
    
  7. an example of some classes which can be used as views. These allow you
    
  8. to structure your views and reuse code by harnessing inheritance and
    
  9. mixins. There are also some generic views for tasks which we'll get to later,
    
  10. but you may want to design your own structure of reusable views which suits
    
  11. your use case. For full details, see the :doc:`class-based views reference
    
  12. documentation</ref/class-based-views/index>`.
    
  13. 
    
  14. .. toctree::
    
  15.    :maxdepth: 1
    
  16. 
    
  17.    intro
    
  18.    generic-display
    
  19.    generic-editing
    
  20.    mixins
    
  21. 
    
  22. Basic examples
    
  23. ==============
    
  24. 
    
  25. Django provides base view classes which will suit a wide range of applications.
    
  26. All views inherit from the :class:`~django.views.generic.base.View` class, which
    
  27. handles linking the view into the URLs, HTTP method dispatching and other
    
  28. common features. :class:`~django.views.generic.base.RedirectView` provides a
    
  29. HTTP redirect, and :class:`~django.views.generic.base.TemplateView` extends the
    
  30. base class to make it also render a template.
    
  31. 
    
  32. 
    
  33. Usage in your URLconf
    
  34. =====================
    
  35. 
    
  36. The most direct way to use generic views is to create them directly in your
    
  37. URLconf. If you're only changing a few attributes on a class-based view, you
    
  38. can pass them into the :meth:`~django.views.generic.base.View.as_view` method
    
  39. call itself::
    
  40. 
    
  41.     from django.urls import path
    
  42.     from django.views.generic import TemplateView
    
  43. 
    
  44.     urlpatterns = [
    
  45.         path('about/', TemplateView.as_view(template_name="about.html")),
    
  46.     ]
    
  47. 
    
  48. Any arguments passed to :meth:`~django.views.generic.base.View.as_view` will
    
  49. override attributes set on the class. In this example, we set ``template_name``
    
  50. on the ``TemplateView``. A similar overriding pattern can be used for the
    
  51. ``url`` attribute on :class:`~django.views.generic.base.RedirectView`.
    
  52. 
    
  53. 
    
  54. Subclassing generic views
    
  55. =========================
    
  56. 
    
  57. The second, more powerful way to use generic views is to inherit from an
    
  58. existing view and override attributes (such as the ``template_name``) or
    
  59. methods (such as ``get_context_data``) in your subclass to provide new values
    
  60. or methods. Consider, for example, a view that just displays one template,
    
  61. ``about.html``. Django has a generic view to do this -
    
  62. :class:`~django.views.generic.base.TemplateView` - so we can subclass it, and
    
  63. override the template name::
    
  64. 
    
  65.     # some_app/views.py
    
  66.     from django.views.generic import TemplateView
    
  67. 
    
  68.     class AboutView(TemplateView):
    
  69.         template_name = "about.html"
    
  70. 
    
  71. Then we need to add this new view into our URLconf.
    
  72. :class:`~django.views.generic.base.TemplateView` is a class, not a function, so
    
  73. we point the URL to the :meth:`~django.views.generic.base.View.as_view` class
    
  74. method instead, which provides a function-like entry to class-based views::
    
  75. 
    
  76.     # urls.py
    
  77.     from django.urls import path
    
  78.     from some_app.views import AboutView
    
  79. 
    
  80.     urlpatterns = [
    
  81.         path('about/', AboutView.as_view()),
    
  82.     ]
    
  83. 
    
  84. 
    
  85. For more information on how to use the built in generic views, consult the next
    
  86. topic on :doc:`generic class-based views</topics/class-based-views/generic-display>`.
    
  87. 
    
  88. .. _supporting-other-http-methods:
    
  89. 
    
  90. Supporting other HTTP methods
    
  91. -----------------------------
    
  92. 
    
  93. Suppose somebody wants to access our book library over HTTP using the views
    
  94. as an API. The API client would connect every now and then and download book
    
  95. data for the books published since last visit. But if no new books appeared
    
  96. since then, it is a waste of CPU time and bandwidth to fetch the books from the
    
  97. database, render a full response and send it to the client. It might be
    
  98. preferable to ask the API when the most recent book was published.
    
  99. 
    
  100. We map the URL to book list view in the URLconf::
    
  101. 
    
  102.     from django.urls import path
    
  103.     from books.views import BookListView
    
  104. 
    
  105.     urlpatterns = [
    
  106.         path('books/', BookListView.as_view()),
    
  107.     ]
    
  108. 
    
  109. And the view::
    
  110. 
    
  111.     from django.http import HttpResponse
    
  112.     from django.views.generic import ListView
    
  113.     from books.models import Book
    
  114. 
    
  115.     class BookListView(ListView):
    
  116.         model = Book
    
  117. 
    
  118.         def head(self, *args, **kwargs):
    
  119.             last_book = self.get_queryset().latest('publication_date')
    
  120.             response = HttpResponse(
    
  121.                 # RFC 1123 date format.
    
  122.                 headers={'Last-Modified': last_book.publication_date.strftime('%a, %d %b %Y %H:%M:%S GMT')},
    
  123.             )
    
  124.             return response
    
  125. 
    
  126. If the view is accessed from a ``GET`` request, an object list is returned in
    
  127. the response (using the ``book_list.html`` template). But if the client issues
    
  128. a ``HEAD`` request, the response has an empty body and the ``Last-Modified``
    
  129. header indicates when the most recent book was published.  Based on this
    
  130. information, the client may or may not download the full object list.
    
  131. 
    
  132. .. _async-class-based-views:
    
  133. 
    
  134. Asynchronous class-based views
    
  135. ==============================
    
  136. 
    
  137. .. versionadded:: 4.1
    
  138. 
    
  139. As well as the synchronous (``def``) method handlers already shown, ``View``
    
  140. subclasses may define asynchronous (``async def``) method handlers to leverage
    
  141. asynchronous code using ``await``::
    
  142. 
    
  143.     import asyncio
    
  144.     from django.http import HttpResponse
    
  145.     from django.views import View
    
  146. 
    
  147.     class AsyncView(View):
    
  148.         async def get(self, request, *args, **kwargs):
    
  149.             # Perform io-blocking view logic using await, sleep for example.
    
  150.             await asyncio.sleep(1)
    
  151.             return HttpResponse("Hello async world!")
    
  152. 
    
  153. Within a single view-class, all user-defined method handlers must be either
    
  154. synchronous, using ``def``, or all asynchronous, using ``async def``. An
    
  155. ``ImproperlyConfigured`` exception will be raised in ``as_view()`` if ``def``
    
  156. and ``async def`` declarations are mixed.
    
  157. 
    
  158. Django will automatically detect asynchronous views and run them in an
    
  159. asynchronous context. You can read more about Django's asynchronous support,
    
  160. and how to best use async views, in :doc:`/topics/async`.