DEV Community

Cover image for Function-Based Views vs Class-Based Views in Django
Max Ong Zong Bao
Max Ong Zong Bao

Posted on • Originally published at maxongzb.com

Function-Based Views vs Class-Based Views in Django

Introduction

undraw content structure 79gj

When I had just started learning Django. There is always a problem for me to choose from.

Which views should I used that is either function-based views or class-based views.

I believe this is one of the core reasons why Django is hard to pick up for beginners.

Therefore I believe that this article could allow you to understand the basic functionality of these views.

To make a choice in your development on which is needed to be based upon your use cases.

Function-Based Views (FBV)

undraw annotation 7das

What is Function-Based Views (FBV)?

Function-Based Views is similar to how you create a function in Python.

The difference instead of calling the function directly.

It takes in an HTTP request which is called request in views.py.

It returns an HTML response based upon the URL that is specified in urls.py to call the function.

If you had just started learning Django.

Function-based views are the first view that you will be introduced by a tutorial from Django Girls or Mozilla Developer Network or Django.

How Does it Look Like?

In the most basic form, a function-based view will look like this which returns a response.

In fbv_1 function a return is used to return a HTML response.

Whereas, for fbv_2 returns a render which uses a pre-created template design called detail.html to generate an HTML response:

from django.http import HttpResponse, HttpResponseNotFound, Http404
from django.shortcuts import render
from polls.models import Poll


def fbv_1(requests):
   if requests:
     return HttpResponse('<h1>Page was found</h1>')
   else:
     return HttpResponseNotFound('<h1>Page not found</h1>')


def fbv_2(request, poll_id):
   try:
     p = Poll.objects.get(pk=poll_id)
   except Poll.DoesNotExist:
     raise Http404("Poll does not exist")
   return render(request, 'polls/detail.html', {'poll': p})

Enter fullscreen mode Exit fullscreen mode

Pros & Cons

Below is based upon my research and experience in working with function-based views.

Pros

  • Ease of teaching
  • Simple to implement
  • Ease of reading due to straight forward nature of the codebase

Cons

  • Unable to extend or customise based upon request condition
  • Hard to reuse code which results in repeat code in another view.

Class-Based Views (CBV)

undraw personal file 222m

Class-based views were introduced to address the inflexibility, code reusability & ease customisation for views.

What is Class-Based Views (CBV)?

A Class-Based Views (CBV) is created for the above reasons.

It is implemented to address common patterns founded in the request conditions.

You can think of CBV as similar to a playbook.

That is used to create diverse or complex views from the request conditions.

This playbook could be founded in Classly Class-Based Views.

To provide you with a better understanding of what is implemented in Django for CBV.

How Does it Look Like?

The most basic form of CBV is when you import the default View from django.views to create a CBV.

As base upon the HTTP request methods like GET, POST or DELETE to return the correct response:

from django.views import View


class CBV(View):
   def get(self, request):
     # Code block for GET request
     pass

   def post(self, request):
     # Code block for POST request
     pass

Enter fullscreen mode Exit fullscreen mode

To create advance or complex version of CBV, there is the built-in Generic Views that address common behaviours

Another is Mixins that deliver specific functionality.

For a deep dive into CBV, head on down to Django documentation Classly Class-Based Views & Class-Based Views in Django for more details about it.

Pros & Cons

Below is based upon my research and experience in working with class-based views.

Pros

  • Ease of customisation through extending the class
  • Code reusability base on Object Orientated Design principles
  • Ease of creating CBV due playbook style of built in Mixin & Generic Views

Cons

  • Requires additional research & testing for the right built-in generic views & mixins if you require an advanced or complex CBV.
  • Harder to read
  • Flow of code is not clear and direct due to abstraction which leads to confusion for developers.

What is the Differences Between FBV vs CBV?

undraw dev productivity umsq

If you require views to be simple, easy to maintain and your problem require a straight forward solution without a lot of customisation pick FBV.

If you require your views to be complex, customisable & reusable pick CBV.

Do note that, there are certain cases to pick you will need to pick CBV.

Especially if you plan to create forms, authentication.

This could also be you are using Django REST Framework to create endpoints.

Conclusion

undraw snap the moment oyn6
I do hope this article can help you to gain a better understanding of both FBV & CBV.

So that it will speed up your learning curve of implementing both FBV & CBV in Django.

Besides that, I hope it provides enough insights to allow you to pick the correct view for your use case.

Lastly, there are multiple schools of thoughts on preferences for either CBV or FBV.

For me, it's more towards using it on use cases that make sense to you.

I believe the research and implementation of CBV can benefit you if you need something done quickly.

If you like this article sign up for my Adventurer's Newsletter for a weekly update in the area of Python, Startup and Web Development.

You can also follow me to get the latest update of my article on Dev

The original post was on Function-Based Views vs Class Based-Views in Django - Reading Time: 5 Mins and cover image by Photo by Dietmar Becker on Unsplash

Reference

Top comments (0)