index.txt 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. =================
  2. Class-based views
  3. =================
  4. .. versionadded:: 1.3
  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 simple tasks which we'll
  10. get to later, but you may want to design your own structure of
  11. reusable views which suits your use case. For full details, see the
  12. :doc:`class-based views reference documentation</ref/class-based-views/index>`.
  13. .. toctree::
  14. :maxdepth: 1
  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 simple HTTP
  24. redirect, and :class:`~django.views.generic.base.TemplateView` extends the base class
  25. 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 ``as_view`` method call itself::
  31. from django.conf.urls import patterns, url, include
  32. from django.views.generic import TemplateView
  33. urlpatterns = patterns('',
  34. (r'^about/', TemplateView.as_view(template_name="about.html")),
  35. )
  36. Any arguments given will override the ``template_name`` on the
  37. A similar overriding pattern can be used for the ``url`` attribute on
  38. :class:`~django.views.generic.base.RedirectView`.
  39. Subclassing generic views
  40. =========================
  41. The second, more powerful way to use generic views is to inherit from an
  42. existing view and override attributes (such as the ``template_name``) or
  43. methods (such as ``get_context_data``) in your subclass to provide new values
  44. or methods. Consider, for example, a view that just displays one template,
  45. ``about.html``. Django has a generic view to do this -
  46. :class:`~django.views.generic.base.TemplateView` - so we can just subclass it,
  47. and override the template name::
  48. # some_app/views.py
  49. from django.views.generic import TemplateView
  50. class AboutView(TemplateView):
  51. template_name = "about.html"
  52. Then we just need to add this new view into our URLconf.
  53. `~django.views.generic.base.TemplateView` is a class, not a function, so we
  54. point the URL to the ``as_view`` class method instead, which provides a
  55. function-like entry to class-based views::
  56. # urls.py
  57. from django.conf.urls import patterns, url, include
  58. from some_app.views import AboutView
  59. urlpatterns = patterns('',
  60. (r'^about/', AboutView.as_view()),
  61. )
  62. For more information on how to use the built in generic views, consult the next
  63. topic on :doc:`generic class based views</topics/class-based-views/generic-display>`.
  64. Decorating class-based views
  65. ============================
  66. .. highlightlang:: python
  67. Since class-based views aren't functions, decorating them works differently
  68. depending on if you're using ``as_view`` or creating a subclass.
  69. Decorating in URLconf
  70. ---------------------
  71. The simplest way of decorating class-based views is to decorate the
  72. result of the :meth:`~django.views.generic.base.View.as_view` method.
  73. The easiest place to do this is in the URLconf where you deploy your view::
  74. from django.contrib.auth.decorators import login_required, permission_required
  75. from django.views.generic import TemplateView
  76. from .views import VoteView
  77. urlpatterns = patterns('',
  78. (r'^about/', login_required(TemplateView.as_view(template_name="secret.html"))),
  79. (r'^vote/', permission_required('polls.can_vote')(VoteView.as_view())),
  80. )
  81. This approach applies the decorator on a per-instance basis. If you
  82. want every instance of a view to be decorated, you need to take a
  83. different approach.
  84. .. _decorating-class-based-views:
  85. Decorating the class
  86. --------------------
  87. To decorate every instance of a class-based view, you need to decorate
  88. the class definition itself. To do this you apply the decorator to the
  89. :meth:`~django.views.generic.base.View.dispatch` method of the class.
  90. A method on a class isn't quite the same as a standalone function, so
  91. you can't just apply a function decorator to the method -- you need to
  92. transform it into a method decorator first. The ``method_decorator``
  93. decorator transforms a function decorator into a method decorator so
  94. that it can be used on an instance method. For example::
  95. from django.contrib.auth.decorators import login_required
  96. from django.utils.decorators import method_decorator
  97. from django.views.generic import TemplateView
  98. class ProtectedView(TemplateView):
  99. template_name = 'secret.html'
  100. @method_decorator(login_required)
  101. def dispatch(self, *args, **kwargs):
  102. return super(ProtectedView, self).dispatch(*args, **kwargs)
  103. In this example, every instance of ``ProtectedView`` will have
  104. login protection.
  105. .. note::
  106. ``method_decorator`` passes ``*args`` and ``**kwargs``
  107. as parameters to the decorated method on the class. If your method
  108. does not accept a compatible set of parameters it will raise a
  109. ``TypeError`` exception.