index.txt 7.2 KB

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