Debian Codegraph @

docs/topics/class-based-views/intro.txt

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