Introduction to class-based views

Class-based views provide an alternative way to implement views as Pythonobjects instead of functions. They do not replace function-based views, buthave certain differences and advantages when compared to function-based views:

  • Organization of code related to specific HTTP methods (GET, POST,etc.) can be addressed by separate methods instead of conditional branching.
  • Object oriented techniques such as mixins (multiple inheritance) can beused to factor code into reusable components.

The relationship and history of generic views, class-based views, and class-based generic views

In the beginning there was only the view function contract, Django passed yourfunction an HttpRequest and expected back anHttpResponse. This was the extent of what Django provided.

Early on it was recognized that there were common idioms and patterns found inview development. Function-based generic views were introduced to abstractthese patterns and ease view development for the common cases.

The problem with function-based generic views is that while they covered thesimple cases well, there was no way to extend or customize them beyond someconfiguration options, limiting their usefulness in many real-worldapplications.

Class-based generic views were created with the same objective asfunction-based generic views, to make view development easier. However, the waythe solution is implemented, through the use of mixins, provides a toolkit thatresults in class-based generic views being more extensible and flexible thantheir function-based counterparts.

If you have tried function based generic views in the past and found themlacking, you should not think of class-based generic views as a class-basedequivalent, but rather as a fresh approach to solving the original problemsthat generic views were meant to solve.

The toolkit of base classes and mixins that Django uses to build class-basedgeneric views are built for maximum flexibility, and as such have many hooks inthe form of default method implementations and attributes that you are unlikelyto be concerned with in the simplest use cases. For example, instead oflimiting you to a class-based attribute for form_class, the implementationuses a get_form method, which calls a get_form_class method, which inits default implementation returns the form_class attribute of the class.This gives you several options for specifying what form to use, from anattribute, to a fully dynamic, callable hook. These options seem to add hollowcomplexity for simple situations, but without them, more advanced designs wouldbe limited.

Using class-based views

At its core, a class-based view allows you to respond to different HTTP requestmethods with different class instance methods, instead of with conditionallybranching code inside a single view function.

So where the code to handle HTTP GET in a view function would looksomething like:

  1. from django.http import HttpResponse
  2.  
  3. def my_view(request):
  4. if request.method == 'GET':
  5. # <view logic>
  6. return HttpResponse('result')

In a class-based view, this would become:

  1. from django.http import HttpResponse
  2. from django.views import View
  3.  
  4. class MyView(View):
  5. def get(self, request):
  6. # <view logic>
  7. return HttpResponse('result')

Because Django’s URL resolver expects to send the request and associatedarguments to a callable function, not a class, class-based views have anas_view() class method which returns afunction that can be called when a request arrives for a URL matching theassociated pattern. The function creates an instance of the class, callssetup() to initialize its attributes, andthen calls its dispatch() method.dispatch looks at the request to determine whether it is a GET,POST, etc, and relays the request to a matching method if one is defined,or raises HttpResponseNotAllowed if not:

  1. # urls.py
  2. from django.urls import path
  3. from myapp.views import MyView
  4.  
  5. urlpatterns = [
  6. path('about/', MyView.as_view()),
  7. ]

It is worth noting that what your method returns is identical to what youreturn from a function-based view, namely some form ofHttpResponse. This means thathttp shortcuts orTemplateResponse objects are valid to useinside a class-based view.

While a minimal class-based view does not require any class attributes toperform its job, class attributes are useful in many class-based designs,and there are two ways to configure or set class attributes.

The first is the standard Python way of subclassing and overriding attributesand methods in the subclass. So that if your parent class had an attributegreeting like this:

  1. from django.http import HttpResponse
  2. from django.views import View
  3.  
  4. class GreetingView(View):
  5. greeting = "Good Day"
  6.  
  7. def get(self, request):
  8. return HttpResponse(self.greeting)

You can override that in a subclass:

  1. class MorningGreetingView(GreetingView):
  2. greeting = "Morning to ya"

Another option is to configure class attributes as keyword arguments to theas_view() call in the URLconf:

  1. urlpatterns = [
  2. path('about/', GreetingView.as_view(greeting="G'day")),
  3. ]

Note

While your class is instantiated for each request dispatched to it, classattributes set through theas_view() entry point areconfigured only once at the time your URLs are imported.

Using mixins

Mixins are a form of multiple inheritance where behaviors and attributes ofmultiple parent classes can be combined.

For example, in the generic class-based views there is a mixin calledTemplateResponseMixin whose primary purposeis to define the methodrender_to_response().When combined with the behavior of the Viewbase class, the result is a TemplateViewclass that will dispatch requests to the appropriate matching methods (abehavior defined in the View base class), and that has arender_to_response()method that uses atemplate_nameattribute to return a TemplateResponseobject (a behavior defined in the TemplateResponseMixin).

Mixins are an excellent way of reusing code across multiple classes, but theycome with some cost. The more your code is scattered among mixins, the harderit will be to read a child class and know what exactly it is doing, and theharder it will be to know which methods from which mixins to override if youare subclassing something that has a deep inheritance tree.

Note also that you can only inherit from one generic view - that is, only oneparent class may inherit from View andthe rest (if any) should be mixins. Trying to inherit from more than one classthat inherits from View - for example, trying to use a form at the top of alist and combining ProcessFormView andListView - won’t work as expected.

Handling forms with class-based views

A basic function-based view that handles forms may look something like this:

  1. from django.http import HttpResponseRedirect
  2. from django.shortcuts import render
  3.  
  4. from .forms import MyForm
  5.  
  6. def myview(request):
  7. if request.method == "POST":
  8. form = MyForm(request.POST)
  9. if form.is_valid():
  10. # <process form cleaned data>
  11. return HttpResponseRedirect('/success/')
  12. else:
  13. form = MyForm(initial={'key': 'value'})
  14.  
  15. return render(request, 'form_template.html', {'form': form})

A similar class-based view might look like:

  1. from django.http import HttpResponseRedirect
  2. from django.shortcuts import render
  3. from django.views import View
  4.  
  5. from .forms import MyForm
  6.  
  7. class MyFormView(View):
  8. form_class = MyForm
  9. initial = {'key': 'value'}
  10. template_name = 'form_template.html'
  11.  
  12. def get(self, request, *args, **kwargs):
  13. form = self.form_class(initial=self.initial)
  14. return render(request, self.template_name, {'form': form})
  15.  
  16. def post(self, request, *args, **kwargs):
  17. form = self.form_class(request.POST)
  18. if form.is_valid():
  19. # <process form cleaned data>
  20. return HttpResponseRedirect('/success/')
  21.  
  22. return render(request, self.template_name, {'form': form})

This is a minimal case, but you can see that you would then have the optionof customizing this view by overriding any of the class attributes, e.g.form_class, via URLconf configuration, or subclassing and overriding one ormore of the methods (or both!).

Decorating class-based views

The extension of class-based views isn’t limited to using mixins. You can alsouse decorators. Since class-based views aren’t functions, decorating them worksdifferently depending on if you’re using as_view() or creating a subclass.

Decorating in URLconf

You can adjust class-based views by decorating the result of theas_view() method. The easiest place to dothis is in the URLconf where you deploy your view:

  1. from django.contrib.auth.decorators import login_required, permission_required
  2. from django.views.generic import TemplateView
  3.  
  4. from .views import VoteView
  5.  
  6. urlpatterns = [
  7. path('about/', login_required(TemplateView.as_view(template_name="secret.html"))),
  8. path('vote/', permission_required('polls.can_vote')(VoteView.as_view())),
  9. ]

This approach applies the decorator on a per-instance basis. If youwant every instance of a view to be decorated, you need to take adifferent approach.

Decorating the class

To decorate every instance of a class-based view, you need to decoratethe class definition itself. To do this you apply the decorator to thedispatch() method of the class.

A method on a class isn’t quite the same as a standalone function, so you can’tjust apply a function decorator to the method – you need to transform it intoa method decorator first. The method_decorator decorator transforms afunction decorator into a method decorator so that it can be used on aninstance method. For example:

  1. from django.contrib.auth.decorators import login_required
  2. from django.utils.decorators import method_decorator
  3. from django.views.generic import TemplateView
  4.  
  5. class ProtectedView(TemplateView):
  6. template_name = 'secret.html'
  7.  
  8. @method_decorator(login_required)
  9. def dispatch(self, *args, **kwargs):
  10. return super().dispatch(*args, **kwargs)

Or, more succinctly, you can decorate the class instead and pass the nameof the method to be decorated as the keyword argument name:

  1. @method_decorator(login_required, name='dispatch')class ProtectedView(TemplateView): template_name = 'secret.html'

If you have a set of common decorators used in several places, you can definea list or tuple of decorators and use this instead of invokingmethod_decorator() multiple times. These two classes are equivalent:

  1. decorators = [never_cache, login_required]
  2.  
  3. @method_decorator(decorators, name='dispatch')
  4. class ProtectedView(TemplateView):
  5. template_name = 'secret.html'
  6.  
  7. @method_decorator(never_cache, name='dispatch')
  8. @method_decorator(login_required, name='dispatch')
  9. class ProtectedView(TemplateView):
  10. template_name = 'secret.html'

The decorators will process a request in the order they are passed to thedecorator. In the example, never_cache() will process the request beforelogin_required().

In this example, every instance of ProtectedView will have loginprotection. These examples use login_required, however, the same behaviorcan be obtained by usingLoginRequiredMixin.

Note

method_decorator passes args and *kwargsas parameters to the decorated method on the class. If your methoddoes not accept a compatible set of parameters it will raise aTypeError exception.