Tag Archives: Django developers

CLASS BASED VIEWS IN DJANGO

Class Based Views in Django:

We often find that Django developers exclusively those new to the framework and even some advanced users choose to use function based views for most projects. This can be attributed firstly to the simplicity of using FBVs and a lack of understanding of the great advantages of using Class Based Views.

In this article we will be highlighting some of the major advantages and the features of CBV.

SOME OF THE PROS OF USING CLASS BASED VIEW:

  • Code reusability – In CBV, a view class can be inherited by another view class and altered for a different use case.
  • Code extendibility – CBV can be extended to include more functionalities using Mixins.
  • Code structuring – In CBVs a class based view helps the developer to respond different http request with different class instance methods instead of conditional branching statements inside a single function based view.

Django class based view provides a class instance method as_view() which serves as an entry point for any generic CBV. Django URL resolver expects to send the request passed through it to a function. The as_view() class instance method in each generic view creates a hook for calling the class just like a method.

As such, the url configuration for calling a CBV follows the pattern below:

urlpatterns = [
url(r’^homepage/’, ClassView.as_view(), name = “url_name”)
]

The as_view() method then calls the dispatch() method which in turn calls the class instance method defined for the applicable http request method if available or throws an HttpResponseNotAllowed exception.

CBV.as_view() ——> CBV.dispatch() ——————–
|       |       |      |  and so on.
v      v        v      v
get post head put

Base class attributes can be overridden in child class as with the standard Python approach. Instead, the new attribute can be passed as an argument to the as_view() method of the CBV.

USING MIXINS:

One of the benefits of using a Class based view its extendibility, this quality is further improved through the use of Mixins.

Mixins are a form of multiple inheritances that lets the combination of behavior from multiple parent classes. They are used to add additional functionality and behavior to classes. Mixins are intended to be inherited and not implemented directly. In CBVs Mixins are passed as leftmost argument while Django generic view classes are placed to the right.

Extending a class view with multiple Mixins can lead to some unforeseen behavior. However, if used with caution, mixins are great tools for adding robust functionalities to a CBV.

For instance:

class NewMixin(object):
def do_whatever(self, *args, **kwargs):
The above mixin is used as below:
from django.views.generic import TemplateView

class FreshViewClass(NewMixin, TemplateView):
def do_something_awesome(self):
continue here

The methods defined in the mixin can be called directly in the FreshViewClass class.