Today’s Offer Enroll today and get access to premium content.
App Store Google Play
Intermediate

What is the difference between function-based views and class-based views in Django?

In Django, views are responsible for processing requests and returning responses. Function-based views (FBVs) are defined as standard Python functions, while class-based views (CBVs) use Python classes to encapsulate view logic.

Key differences include:

  1. Structure: FBVs are simpler and easier for basic views, while CBVs are more organized and reusable.
  2. Extensibility: CBVs allow for inheritance and mixins, making it easier to build complex functionality.

Example of a function-based view:

from django.http import HttpResponse
def my_view(request):
    return HttpResponse('Hello, World!')

Example of a class-based view:

from django.views import View
class MyView(View):
    def get(self, request):
        return HttpResponse('Hello, World!')