DEV Community

gabbyprecious
gabbyprecious

Posted on

Class-Based Views or Function-Based Views. And When?

The concept of class-based views in Django is reserved as an advanced coder in Django method. So what happens when you come across it as a beginner? Class-based views and function-based views are used for the same reasons for different approaches.

Just like their name signifies, class-based views are created with the class structure in python(or Django) and uses methods, while function-based are written as functions and uses condition statements.

Function-Based View

Function-Based Views (FBV) are just like basic functions that receive parameters in the form of requests and return a response. Function-based views were the first type of views implemented in Django. Here’s a simple FBV for a login view:

from django.contrib.auth import authenticate, login

def login(request):
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(request, username=username, password=password)
    if user is not None:
        login(request, user)
    else:
       return("please sign up")

Pros

  • It’s simple to understand and implement.
  • Perfect for basic non-repeated functionality.

Cons

  • Uses conditions for HTTP methods
  • Can’t be reused
  • Goes against DRY principles

Class-Based View

Class-Based Views (CBV) were introduced to be used in cases to avoid repetitions, following the DRY (Don’t Repeat Yourself) principle as a CBV can be inherited by another CBV view. Keep in mind, CBV does not replace FBV, but rather was built to reduce repetition of views functions, and allows view templatizing and reuse, as it uses inheritance and mixin.

Organising code in CBV into different HTTP methods is done via methods compared to conditions as in FBV. Here is an example:

from django.views.generic import View

class LoginView(View):
    def post(self, request):
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)

        if user is not None:
              login(request, user)
        else:
            return("please sign up")

Here, def post() is a method representing a HTTP method, A class could have several method for different HTTP method(def get, def delete and def patch).

Also, here is an example of inheritance within CBV, if you want to greet the user right when they log in and when they log out, with a different reply.

from django.http import HttpResponse
from django.views import View

class LoginView(View):
    greeting = "Welcome!"

    def get(self, request):
        return HttpResponse(self.greeting)

class LogoutView(LoginView):
    greeting = "We will miss you!" 

Pros

  • Supports the use of inheritance and mixin for views
  • Allows reuse
  • Follows the DRY principle

Cons

  • Hard to read and implement
  • Use of view decorators require extra import or method override

Generic Class Based Views?

Django takes pride in making things easy and faster to implement and get work done. Django introduced generic class-based view which is built on the concept of class-based views.

Generic class-based views are Django’s built-in views that can be implemented by a developer, it’s consists of common views integrated into web development. It’s a boilerplate that helps to prevent writing common functionalities again. Functionalities like form handling, creating new objects and listing out queries.

Here’s an example:

#code from django docs

from django.views.generic import ListView
from books.models import Publisher

class PublisherList(ListView):
    model = Publisher

This view performs a query on the publisher table and returns the response in a list manner.

And When?

When do you make a view CBV or FBV, well that’s up to you? What functionality does it perform? Will it be reused? Is it complex or simple? Is it a common function implemented in most web applications? (Here you can implement generic class-based views).

Here is a simple format I follow when deciding on what type of view to implement:

Conclusion:

Your use of any view is dependent on your choice, your implementation, and the cons and pros of your decision.

Further Reading

  1. https://docs.djangoproject.com/en/3.0/topics/class-based-views/
  2. https://docs.djangoproject.com/en/3.0/topics/class-based-views/generic-display/

Top comments (0)