index.txt 5.9 KB

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