index.txt 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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. generic-display
  15. generic-editing
  16. mixins
  17. Basic examples
  18. ==============
  19. Django provides base view classes which will suit a wide range of applications.
  20. All views inherit from the :class:`~django.views.generic.base.View` class, which
  21. handles linking the view in to the URLs, HTTP method dispatching and other
  22. simple features. :class:`~django.views.generic.base.RedirectView` is for a simple HTTP
  23. redirect, and :class:`~django.views.generic.base.TemplateView` extends the base class
  24. to make it also render a template.
  25. Simple usage in your URLconf
  26. ============================
  27. The simplest way to use generic views is to create them directly in your
  28. URLconf. If you're only changing a few simple attributes on a class-based view,
  29. you can simply pass them into the ``as_view`` method call itself::
  30. from django.conf.urls import patterns, url, include
  31. from django.views.generic import TemplateView
  32. urlpatterns = patterns('',
  33. (r'^about/', TemplateView.as_view(template_name="about.html")),
  34. )
  35. Any arguments given will override the ``template_name`` on the
  36. A similar overriding pattern can be used for the ``url`` attribute on
  37. :class:`~django.views.generic.base.RedirectView`.
  38. Subclassing generic views
  39. =========================
  40. The second, more powerful way to use generic views is to inherit from an
  41. existing view and override attributes (such as the ``template_name``) or
  42. methods (such as ``get_context_data``) in your subclass to provide new values
  43. or methods. Consider, for example, a view that just displays one template,
  44. ``about.html``. Django has a generic view to do this -
  45. :class:`~django.views.generic.base.TemplateView` - so we can just subclass it,
  46. and override the template name::
  47. # some_app/views.py
  48. from django.views.generic import TemplateView
  49. class AboutView(TemplateView):
  50. template_name = "about.html"
  51. Then we just need to add this new view into our URLconf.
  52. `~django.views.generic.base.TemplateView` is a class, not a function, so we
  53. point the URL to the ``as_view`` class method instead, which provides a
  54. function-like entry to class-based views::
  55. # urls.py
  56. from django.conf.urls import patterns, url, include
  57. from some_app.views import AboutView
  58. urlpatterns = patterns('',
  59. (r'^about/', AboutView.as_view()),
  60. )
  61. For more information on how to use the built in generic views, consult the next
  62. topic on :doc:`generic class based views</topics/class-based-views/generic-display>`.
  63. .. _supporting-other-http-methods:
  64. Supporting other HTTP methods
  65. -----------------------------
  66. Suppose somebody wants to access our book library over HTTP using the views
  67. as an API. The API client would connect every now and then and download book
  68. data for the books published since last visit. But if no new books appeared
  69. since then, it is a waste of CPU time and bandwidth to fetch the books from the
  70. database, render a full response and send it to the client. It might be
  71. preferable to ask the API when the most recent book was published.
  72. We map the URL to book list view in the URLconf::
  73. from django.conf.urls import patterns
  74. from books.views import BookListView
  75. urlpatterns = patterns('',
  76. (r'^books/$', BookListView.as_view()),
  77. )
  78. And the view::
  79. from django.http import HttpResponse
  80. from django.views.generic import ListView
  81. from books.models import Book
  82. class BookListView(ListView):
  83. model = Book
  84. def head(self, *args, **kwargs):
  85. last_book = self.get_queryset().latest('publication_date')
  86. response = HttpResponse('')
  87. # RFC 1123 date format
  88. response['Last-Modified'] = last_book.publication_date.strftime('%a, %d %b %Y %H:%M:%S GMT')
  89. return response
  90. If the view is accessed from a ``GET`` request, a plain-and-simple object
  91. list is returned in the response (using ``book_list.html`` template). But if
  92. the client issues a ``HEAD`` request, the response has an empty body and
  93. the ``Last-Modified`` header indicates when the most recent book was published.
  94. Based on this information, the client may or may not download the full object
  95. list.
  96. Decorating class-based views
  97. ============================
  98. .. highlightlang:: python
  99. Since class-based views aren't functions, decorating them works differently
  100. depending on if you're using ``as_view`` or creating a subclass.
  101. Decorating in URLconf
  102. ---------------------
  103. The simplest way of decorating class-based views is to decorate the
  104. result of the :meth:`~django.views.generic.base.View.as_view` method.
  105. The easiest place to do this is in the URLconf where you deploy your view::
  106. from django.contrib.auth.decorators import login_required, permission_required
  107. from django.views.generic import TemplateView
  108. from .views import VoteView
  109. urlpatterns = patterns('',
  110. (r'^about/', login_required(TemplateView.as_view(template_name="secret.html"))),
  111. (r'^vote/', permission_required('polls.can_vote')(VoteView.as_view())),
  112. )
  113. This approach applies the decorator on a per-instance basis. If you
  114. want every instance of a view to be decorated, you need to take a
  115. different approach.
  116. .. _decorating-class-based-views:
  117. Decorating the class
  118. --------------------
  119. To decorate every instance of a class-based view, you need to decorate
  120. the class definition itself. To do this you apply the decorator to the
  121. :meth:`~django.views.generic.base.View.dispatch` method of the class.
  122. A method on a class isn't quite the same as a standalone function, so
  123. you can't just apply a function decorator to the method -- you need to
  124. transform it into a method decorator first. The ``method_decorator``
  125. decorator transforms a function decorator into a method decorator so
  126. that it can be used on an instance method. For example::
  127. from django.contrib.auth.decorators import login_required
  128. from django.utils.decorators import method_decorator
  129. from django.views.generic import TemplateView
  130. class ProtectedView(TemplateView):
  131. template_name = 'secret.html'
  132. @method_decorator(login_required)
  133. def dispatch(self, *args, **kwargs):
  134. return super(ProtectedView, self).dispatch(*args, **kwargs)
  135. In this example, every instance of ``ProtectedView`` will have
  136. login protection.
  137. .. note::
  138. ``method_decorator`` passes ``*args`` and ``**kwargs``
  139. as parameters to the decorated method on the class. If your method
  140. does not accept a compatible set of parameters it will raise a
  141. ``TypeError`` exception.