index.txt 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  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 simple tasks which we'll
  9. get to later, but you may want to design your own structure of
  10. reusable views which suits your use case. For full details, see the
  11. :doc:`class-based views reference 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 in to the URLs, HTTP method dispatching and other
  23. simple features. :class:`~django.views.generic.base.RedirectView` is for a
  24. simple HTTP redirect, and :class:`~django.views.generic.base.TemplateView`
  25. extends the base class to make it also render a template.
  26. Simple usage in your URLconf
  27. ============================
  28. The simplest way to use generic views is to create them directly in your
  29. URLconf. If you're only changing a few simple attributes on a class-based view,
  30. you can simply pass them into the
  31. :meth:`~django.views.generic.base.View.as_view` method call itself::
  32. from django.conf.urls import url
  33. from django.views.generic import TemplateView
  34. urlpatterns = [
  35. url(r'^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 just subclass it,
  49. and 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 just need to add this new view into our URLconf.
  55. :class:`~django.views.generic.base.TemplateView` is a class, not a function,
  56. so we point the URL to the :meth:`~django.views.generic.base.View.as_view`
  57. class method instead, which provides a function-like entry to class-based
  58. views::
  59. # urls.py
  60. from django.conf.urls import url
  61. from some_app.views import AboutView
  62. urlpatterns = [
  63. url(r'^about/', AboutView.as_view()),
  64. ]
  65. For more information on how to use the built in generic views, consult the next
  66. topic on :doc:`generic class based views</topics/class-based-views/generic-display>`.
  67. .. _supporting-other-http-methods:
  68. Supporting other HTTP methods
  69. -----------------------------
  70. Suppose somebody wants to access our book library over HTTP using the views
  71. as an API. The API client would connect every now and then and download book
  72. data for the books published since last visit. But if no new books appeared
  73. since then, it is a waste of CPU time and bandwidth to fetch the books from the
  74. database, render a full response and send it to the client. It might be
  75. preferable to ask the API when the most recent book was published.
  76. We map the URL to book list view in the URLconf::
  77. from django.conf.urls import url
  78. from books.views import BookListView
  79. urlpatterns = [
  80. url(r'^books/$', BookListView.as_view()),
  81. ]
  82. And the view::
  83. from django.http import HttpResponse
  84. from django.views.generic import ListView
  85. from books.models import Book
  86. class BookListView(ListView):
  87. model = Book
  88. def head(self, *args, **kwargs):
  89. last_book = self.get_queryset().latest('publication_date')
  90. response = HttpResponse('')
  91. # RFC 1123 date format
  92. response['Last-Modified'] = last_book.publication_date.strftime('%a, %d %b %Y %H:%M:%S GMT')
  93. return response
  94. If the view is accessed from a ``GET`` request, a plain-and-simple object
  95. list is returned in the response (using ``book_list.html`` template). But if
  96. the client issues a ``HEAD`` request, the response has an empty body and
  97. the ``Last-Modified`` header indicates when the most recent book was published.
  98. Based on this information, the client may or may not download the full object
  99. list.