Sobes.tech
Junior — Middle

Explain the concept of CBV in Django framework and how it differs from FBV.

sobes.tech AI

Answer from AI

In Django, there are two main approaches to writing views: Function-Based Views (FBV) and Class-Based Views (CBV).

FBV (Function-Based Views) are regular Python functions that accept an HTTP request and return an HTTP response. They are simple and straightforward, suitable for basic cases.

CBV (Class-Based Views) are classes that encapsulate request handling logic. They allow inheritance, method overriding, and code reuse. CBVs are often used for standard operations such as listing objects, creating, updating, and deleting (CRUD).

Main differences:

  • Structure: FBV are functions, CBV are classes.
  • Reusability: CBV make it easy to extend and override behavior through inheritance.
  • Code organization: CBV organize code into methods, improving readability and maintainability.

Example of a simple FBV:

from django.http import HttpResponse

def hello(request):
    return HttpResponse('Hello, world!')

Equivalent CBV example:

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

class HelloView(View):
    def get(self, request):
        return HttpResponse('Hello, world!')

CBVs are especially useful when you need to handle different HTTP methods (GET, POST, etc.) within a single class.