intro.txt 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. =================================
  2. Introduction to class-based views
  3. =================================
  4. Class-based views provide an alternative way to implement views as Python
  5. objects instead of functions. They do not replace function-based views, but
  6. have certain differences and advantages when compared to function-based views:
  7. * Organization of code related to specific HTTP methods (``GET``, ``POST``,
  8. etc.) can be addressed by separate methods instead of conditional branching.
  9. * Object oriented techniques such as mixins (multiple inheritance) can be
  10. used to factor code into reusable components.
  11. The relationship and history of generic views, class-based views, and class-based generic views
  12. ===============================================================================================
  13. In the beginning there was only the view function contract, Django passed your
  14. function an :class:`~django.http.HttpRequest` and expected back an
  15. :class:`~django.http.HttpResponse`. This was the extent of what Django provided.
  16. Early on it was recognized that there were common idioms and patterns found in
  17. view development. Function-based generic views were introduced to abstract
  18. these patterns and ease view development for the common cases.
  19. The problem with function-based generic views is that while they covered the
  20. simple cases well, there was no way to extend or customize them beyond some
  21. configuration options, limiting their usefulness in many real-world
  22. applications.
  23. Class-based generic views were created with the same objective as
  24. function-based generic views, to make view development easier. However, the way
  25. the solution is implemented, through the use of mixins, provides a toolkit that
  26. results in class-based generic views being more extensible and flexible than
  27. their function-based counterparts.
  28. If you have tried function based generic views in the past and found them
  29. lacking, you should not think of class-based generic views as a class-based
  30. equivalent, but rather as a fresh approach to solving the original problems
  31. that generic views were meant to solve.
  32. The toolkit of base classes and mixins that Django uses to build class-based
  33. generic views are built for maximum flexibility, and as such have many hooks in
  34. the form of default method implementations and attributes that you are unlikely
  35. to be concerned with in the simplest use cases. For example, instead of
  36. limiting you to a class-based attribute for ``form_class``, the implementation
  37. uses a ``get_form`` method, which calls a ``get_form_class`` method, which in
  38. its default implementation returns the ``form_class`` attribute of the class.
  39. This gives you several options for specifying what form to use, from an
  40. attribute, to a fully dynamic, callable hook. These options seem to add hollow
  41. complexity for simple situations, but without them, more advanced designs would
  42. be limited.
  43. Using class-based views
  44. =======================
  45. At its core, a class-based view allows you to respond to different HTTP request
  46. methods with different class instance methods, instead of with conditionally
  47. branching code inside a single view function.
  48. So where the code to handle HTTP ``GET`` in a view function would look
  49. something like::
  50. from django.http import HttpResponse
  51. def my_view(request):
  52. if request.method == "GET":
  53. # <view logic>
  54. return HttpResponse("result")
  55. In a class-based view, this would become::
  56. from django.http import HttpResponse
  57. from django.views import View
  58. class MyView(View):
  59. def get(self, request):
  60. # <view logic>
  61. return HttpResponse("result")
  62. Because Django's URL resolver expects to send the request and associated
  63. arguments to a callable function, not a class, class-based views have an
  64. :meth:`~django.views.generic.base.View.as_view` class method which returns a
  65. function that can be called when a request arrives for a URL matching the
  66. associated pattern. The function creates an instance of the class, calls
  67. :meth:`~django.views.generic.base.View.setup` to initialize its attributes, and
  68. then calls its :meth:`~django.views.generic.base.View.dispatch` method.
  69. ``dispatch`` looks at the request to determine whether it is a ``GET``,
  70. ``POST``, etc, and relays the request to a matching method if one is defined,
  71. or raises :class:`~django.http.HttpResponseNotAllowed` if not::
  72. # urls.py
  73. from django.urls import path
  74. from myapp.views import MyView
  75. urlpatterns = [
  76. path("about/", MyView.as_view()),
  77. ]
  78. It is worth noting that what your method returns is identical to what you
  79. return from a function-based view, namely some form of
  80. :class:`~django.http.HttpResponse`. This means that
  81. :doc:`http shortcuts </topics/http/shortcuts>` or
  82. :class:`~django.template.response.TemplateResponse` objects are valid to use
  83. inside a class-based view.
  84. While a minimal class-based view does not require any class attributes to
  85. perform its job, class attributes are useful in many class-based designs,
  86. and there are two ways to configure or set class attributes.
  87. The first is the standard Python way of subclassing and overriding attributes
  88. and methods in the subclass. So that if your parent class had an attribute
  89. ``greeting`` like this::
  90. from django.http import HttpResponse
  91. from django.views import View
  92. class GreetingView(View):
  93. greeting = "Good Day"
  94. def get(self, request):
  95. return HttpResponse(self.greeting)
  96. You can override that in a subclass::
  97. class MorningGreetingView(GreetingView):
  98. greeting = "Morning to ya"
  99. Another option is to configure class attributes as keyword arguments to the
  100. :meth:`~django.views.generic.base.View.as_view` call in the URLconf::
  101. urlpatterns = [
  102. path("about/", GreetingView.as_view(greeting="G'day")),
  103. ]
  104. .. note::
  105. While your class is instantiated for each request dispatched to it, class
  106. attributes set through the
  107. :meth:`~django.views.generic.base.View.as_view` entry point are
  108. configured only once at the time your URLs are imported.
  109. Using mixins
  110. ============
  111. Mixins are a form of multiple inheritance where behaviors and attributes of
  112. multiple parent classes can be combined.
  113. For example, in the generic class-based views there is a mixin called
  114. :class:`~django.views.generic.base.TemplateResponseMixin` whose primary purpose
  115. is to define the method
  116. :meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response`.
  117. When combined with the behavior of the :class:`~django.views.generic.base.View`
  118. base class, the result is a :class:`~django.views.generic.base.TemplateView`
  119. class that will dispatch requests to the appropriate matching methods (a
  120. behavior defined in the ``View`` base class), and that has a
  121. :meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response`
  122. method that uses a
  123. :attr:`~django.views.generic.base.TemplateResponseMixin.template_name`
  124. attribute to return a :class:`~django.template.response.TemplateResponse`
  125. object (a behavior defined in the ``TemplateResponseMixin``).
  126. Mixins are an excellent way of reusing code across multiple classes, but they
  127. come with some cost. The more your code is scattered among mixins, the harder
  128. it will be to read a child class and know what exactly it is doing, and the
  129. harder it will be to know which methods from which mixins to override if you
  130. are subclassing something that has a deep inheritance tree.
  131. Note also that you can only inherit from one generic view - that is, only one
  132. parent class may inherit from :class:`~django.views.generic.base.View` and
  133. the rest (if any) should be mixins. Trying to inherit from more than one class
  134. that inherits from ``View`` - for example, trying to use a form at the top of a
  135. list and combining :class:`~django.views.generic.edit.ProcessFormView` and
  136. :class:`~django.views.generic.list.ListView` - won't work as expected.
  137. Handling forms with class-based views
  138. =====================================
  139. A basic function-based view that handles forms may look something like this::
  140. from django.http import HttpResponseRedirect
  141. from django.shortcuts import render
  142. from .forms import MyForm
  143. def myview(request):
  144. if request.method == "POST":
  145. form = MyForm(request.POST)
  146. if form.is_valid():
  147. # <process form cleaned data>
  148. return HttpResponseRedirect("/success/")
  149. else:
  150. form = MyForm(initial={"key": "value"})
  151. return render(request, "form_template.html", {"form": form})
  152. A similar class-based view might look like::
  153. from django.http import HttpResponseRedirect
  154. from django.shortcuts import render
  155. from django.views import View
  156. from .forms import MyForm
  157. class MyFormView(View):
  158. form_class = MyForm
  159. initial = {"key": "value"}
  160. template_name = "form_template.html"
  161. def get(self, request, *args, **kwargs):
  162. form = self.form_class(initial=self.initial)
  163. return render(request, self.template_name, {"form": form})
  164. def post(self, request, *args, **kwargs):
  165. form = self.form_class(request.POST)
  166. if form.is_valid():
  167. # <process form cleaned data>
  168. return HttpResponseRedirect("/success/")
  169. return render(request, self.template_name, {"form": form})
  170. This is a minimal case, but you can see that you would then have the option
  171. of customizing this view by overriding any of the class attributes, e.g.
  172. ``form_class``, via URLconf configuration, or subclassing and overriding one or
  173. more of the methods (or both!).
  174. Decorating class-based views
  175. ============================
  176. The extension of class-based views isn't limited to using mixins. You can also
  177. use decorators. Since class-based views aren't functions, decorating them works
  178. differently depending on if you're using ``as_view()`` or creating a subclass.
  179. Decorating in URLconf
  180. ---------------------
  181. You can adjust class-based views by decorating the result of the
  182. :meth:`~django.views.generic.base.View.as_view` method. The easiest place to do
  183. this is in the URLconf where you deploy your view::
  184. from django.contrib.auth.decorators import login_required, permission_required
  185. from django.views.generic import TemplateView
  186. from .views import VoteView
  187. urlpatterns = [
  188. path("about/", login_required(TemplateView.as_view(template_name="secret.html"))),
  189. path("vote/", permission_required("polls.can_vote")(VoteView.as_view())),
  190. ]
  191. This approach applies the decorator on a per-instance basis. If you
  192. want every instance of a view to be decorated, you need to take a
  193. different approach.
  194. .. _decorating-class-based-views:
  195. Decorating the class
  196. --------------------
  197. To decorate every instance of a class-based view, you need to decorate
  198. the class definition itself. To do this you apply the decorator to the
  199. :meth:`~django.views.generic.base.View.dispatch` method of the class.
  200. A method on a class isn't quite the same as a standalone function, so you can't
  201. just apply a function decorator to the method -- you need to transform it into
  202. a method decorator first. The ``method_decorator`` decorator transforms a
  203. function decorator into a method decorator so that it can be used on an
  204. instance method. For example::
  205. from django.contrib.auth.decorators import login_required
  206. from django.utils.decorators import method_decorator
  207. from django.views.generic import TemplateView
  208. class ProtectedView(TemplateView):
  209. template_name = "secret.html"
  210. @method_decorator(login_required)
  211. def dispatch(self, *args, **kwargs):
  212. return super().dispatch(*args, **kwargs)
  213. Or, more succinctly, you can decorate the class instead and pass the name
  214. of the method to be decorated as the keyword argument ``name``::
  215. @method_decorator(login_required, name="dispatch")
  216. class ProtectedView(TemplateView):
  217. template_name = "secret.html"
  218. If you have a set of common decorators used in several places, you can define
  219. a list or tuple of decorators and use this instead of invoking
  220. ``method_decorator()`` multiple times. These two classes are equivalent::
  221. decorators = [never_cache, login_required]
  222. @method_decorator(decorators, name="dispatch")
  223. class ProtectedView(TemplateView):
  224. template_name = "secret.html"
  225. @method_decorator(never_cache, name="dispatch")
  226. @method_decorator(login_required, name="dispatch")
  227. class ProtectedView(TemplateView):
  228. template_name = "secret.html"
  229. The decorators will process a request in the order they are passed to the
  230. decorator. In the example, ``never_cache()`` will process the request before
  231. ``login_required()``.
  232. In this example, every instance of ``ProtectedView`` will have login
  233. protection. These examples use ``login_required``, however, the same behavior
  234. can be obtained by using
  235. :class:`~django.contrib.auth.mixins.LoginRequiredMixin`.
  236. .. note::
  237. ``method_decorator`` passes ``*args`` and ``**kwargs``
  238. as parameters to the decorated method on the class. If your method
  239. does not accept a compatible set of parameters it will raise a
  240. ``TypeError`` exception.