Function-Based Views vs Class-Based Views in Django
Tags: python, beginners, webdev, django
Published: 2019-12-15 18:05:29

# Introduction
![undraw content structure 79gj][1]

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][2]

## 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][3] or [Mozilla Developer Network][4] or [Django][5].

## 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:
 
```python
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})

```

## 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][6]

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][7].

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][8] like `GET`, `POST` or `DELETE` to return the correct response:

```python
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

```

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

Another is [Mixins][10] that deliver **specific** functionality.

For a deep dive into CBV, head on down to [Django documentation][11] [Classly Class-Based Views][7] & [Class-Based Views in Django][12] 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][13] 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][14]

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][15] to create endpoints.

# Conclusion
![undraw snap the moment oyn6][16]
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](https://maxongzb.activehosted.com/f/1) 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](https://www.maxongzb.com/function-based-views-vs-class-based-views-in-django-reading-time-5-mins/) and cover image by [Photo by Dietmar Becker on Unsplash](https://unsplash.com/photos/8Zt0xOOK4nI)

# Reference
* [Undraw][17]
* [Django Girls][3]
* [Mozilla Developer Network][4] 
* [Django][5]
* [Classly Class-Based Views][7]
* [HTTP Request Methods][8]
* [Built-in Generic Views][9]
* [Class-Based Views][11] 
* [Class-Based Views in Django][12]
* [Object Orientated Design][13] 
* [Django REST Framework][15]
* [Marcus: Django Class-Based Views vs Function-Based Views][18]
* [Concisecoder: Django Function-Based Views vs Class-Based Views][19]
* [Simple is Better Than Complex: Class-Based Views vs Function Based Views][20]


[1]: //images.ctfassets.net/ly2f59p4unnn/7KhqaCqNJbWrw000X0dHaC/8b16385e78c60120c85205f8a9bb4b7b/undraw_content_structure_79gj.png
[2]: //images.ctfassets.net/ly2f59p4unnn/28EW8TxPXLNeYfC6y6KoRP/fa856ad89fa08cb8e268053e490d250a/undraw_annotation_7das.png
[3]: https://tutorial.djangogirls.org/en/
[4]: https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Introduction
[5]: https://docs.djangoproject.com/en/3.0/topics/http/views/
[6]: //images.ctfassets.net/ly2f59p4unnn/5SI7aVZluqIHRgF0EBSL6u/db549c3a0de700e86cb80471197f27f7/undraw_personal_file_222m.png
[7]: http://ccbv.co.uk/
[8]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods
[9]: https://docs.djangoproject.com/en/3.0/topics/class-based-views/generic-display/
[10]: https://docs.djangoproject.com/en/3.0/ref/class-based-views/mixins/
[11]: https://docs.djangoproject.com/en/3.0/ref/class-based-views/
[12]: https://medium.com/all-about-django/class-based-views-in-django-89108c1f51fb
[13]: https://www.geeksforgeeks.org/oops-object-oriented-design/
[14]: //images.ctfassets.net/ly2f59p4unnn/6R9h1XOjuYwltKrzbwg86h/7ee1d728301261690f3d5714c2e71c95/undraw_dev_productivity_umsq.png
[15]: https://www.django-rest-framework.org/
[16]: //images.ctfassets.net/ly2f59p4unnn/7Kkyt26Moup3f8We5h1Rj7/990cdb38feb53e21c3cbf7c95012672e/undraw_snap_the_moment_oyn6.png
[17]: https://undraw.co/illustrations
[18]: https://coderbook.com/@marcus/djangos-class-based-views-vs-function-based-views/
[19]: http://concisecoder.io/2018/12/01/django-function-based-views-vs-class-based-views/
[20]: https://simpleisbetterthancomplex.com/article/2017/03/21/class-based-views-vs-function-based-views.html