A Quick Guide to Using Django Class Based Views

by Applied Informatics

 Djangos class-based generic views provide abstract classes implementing common web development tasks. These are very powerful, and heavily utilize Python’s object orientation and multiple inheritance in order to be extensible. They provide utilities which can be mixed into the much more complex views.

 

Django with generic views perform the following,

  • Process common simple tasks redirected to a different page and render template.
  • Display list and detail pages for a single object.
  • Date based objects.
  • Allow users to create, update and delete objects – with or without authorization.

These functionalities taken together makes web development a lot easier. You can perform a lot of functionalities by using Class Based Views:

Below is the sample Class Based View in Django:

#views.py
from django.http import HttpResponse
from django.views.generic import View

class MyView(View):
def get(self, request):
# <view logic>
return HttpResponse('result')

Because Django’s URL resolver expects to send the request and associated arguments to a callable function, not a class, class-based views have an as_view() class method which serves as the callable entry point to your class. The as_view entry point creates an instance of your class and calls its dispatch() method. Dispatch looks at the request to determine whether it is a GET, POST, etc.

# urls.py
from django.conf.urls import patterns
from myapp.views import MyView

urlpatterns = patterns('',
 (r'^about/', MyView.as_view()),

Using Mixins

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

For example, in generic class-based views there is a mixin called TemplateResponseMixin whose primary purpose is to define the method render_to_response(). When combined with behavior of View base class, result is a TemplateView class that will dispatch requests to the appropriate matching methods (a behavior defined in View base class), and that has a render_to_response() method that uses a template_name attribute to return a TemplateResponse object (a behavior defined in the TemplateResponseMixin).

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

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

Example:

from django.contrib.auth.decorators import login_required

class LoginRequiredMixin(object):
@classmethod
def as_view(cls, **initkwargs):
view = super(LoginRequiredMixin, cls).as_view(**initkwargs)
return login_required(view)

class MyView(LoginRequiredMixin, ...):
# this is a generic view
...

Decorating Class Based Views

Decorating in URLconf:

The simplest way of decorating class-based views is to decorate result of as_view() method. The easiest place to do this is in the URLconf where you deploy your view:

from django.contrib.auth.decorators import login_required, permission_required
from django.views.generic import TemplateView

from .views import VoteView

urlpatterns = patterns('',
(r'^about/', login_required(TemplateView.as_view(template_name="secret.html"))),
(r'^vote/', permission_required('polls.can_vote')(VoteView.as_view())),
)

Class based views do not replace function-based views, but have certain differences and advantages when compared to them,

  • 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 be used to factor code into reusable components.

Class-based views provide an alternative way to implement views as Python objects instead of functions.

Leave a Reply

Your email address will not be published. Required fields are marked *

Tools & Practices

Tools and Technologies we use at Applied

Contact us now

Popular Posts