Django Tutorial

Django Create A Complete Project

Django Template

Django Database Query

Django Form

Django Authentication and Permission Management

Django unittest

Django Advanced

Django's FBV And CBV Mode

In this tutorial, we'll compare and learn how to use Django's Function-Based Views (FBV) and Class-Based Views (CBV) for creating views in your Django project.

Prerequisites:

  • Basic knowledge of Python
  • Familiarity with Django framework
  • A Django project set up and running

Function-Based Views (FBV):

Function-Based Views are simple functions that accept a request object and return an HttpResponse object. They are the traditional way of defining views in Django.

Example of a simple FBV:

from django.http import HttpResponse

def my_view(request):
    return HttpResponse("Hello, World!")

Class-Based Views (CBV):

Class-Based Views are built on top of Python's classes and provide a more structured and reusable way to create views. They can be extended and customized using inheritance and mixin classes.

Example of a simple CBV:

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

class MyView(View):
    def get(self, request):
        return HttpResponse("Hello, World!")

Creating a List View:

  • Function-Based View:
from django.shortcuts import render
from .models import MyModel

def my_list_view(request):
    items = MyModel.objects.all()
    context = {'items': items}
    return render(request, 'myapp/my_list_view.html', context)
  • Class-Based View:
from django.views.generic import ListView
from .models import MyModel

class MyListView(ListView):
    model = MyModel
    template_name = 'myapp/my_list_view.html'
    context_object_name = 'items'

Creating a Detail View:

  • Function-Based View:
from django.shortcuts import render, get_object_or_404
from .models import MyModel

def my_detail_view(request, pk):
    item = get_object_or_404(MyModel, pk=pk)
    context = {'item': item}
    return render(request, 'myapp/my_detail_view.html', context)
  • Class-Based View:
from django.views.generic import DetailView
from .models import MyModel

class MyDetailView(DetailView):
    model = MyModel
    template_name = 'myapp/my_detail_view.html'
    context_object_name = 'item'

URL Patterns for FBV and CBV:

  • For Function-Based Views, the URL pattern is straightforward:
from django.urls import path
from . import views

urlpatterns = [
    path('my_list_view/', views.my_list_view, name='my_list_view'),
    path('my_detail_view/<int:pk>/', views.my_detail_view, name='my_detail_view'),
]
  • For Class-Based Views, use the .as_view() method in the URL pattern:
from django.urls import path
from . import views

urlpatterns = [
    path('my_list_view/', views.MyListView.as_view(), name='my_list_view'),
    path('my_detail_view/<int:pk>/', views.MyDetailView.as_view(), name='my_detail_view'),
]

Advantages of CBV over FBV:

  • Reusability: CBVs allow you to reuse common view functionalities using inheritance and mixin classes.
  • Cleaner code: CBVs can help you organize your code better by splitting different HTTP methods into separate class methods.

In conclusion, both Function-Based Views and Class-Based Views have their own advantages and use cases. FBVs are simpler and more flexible, while CBVs provide more structure and reusability. Depending on your specific requirements, you can choose the appropriate approach for your Django project.

  1. Django FBV example code:

    • Description: Implement a simple Function-Based View in Django to understand the basic structure and functionality.
    • Code Example:
      from django.shortcuts import render
      from django.http import HttpResponse
      
      def my_view(request):
          return HttpResponse("Hello, this is a Function-Based View!")
      
  2. Mixins in Django Class-Based Views:

    • Description: Learn how to use mixins in CBVs to reuse and extend functionality across multiple views.
    • Code Example:
      from django.contrib.auth.mixins import LoginRequiredMixin
      
      class MyView(LoginRequiredMixin, View):
          # Your view logic here
      
  3. Generic Class-Based Views in Django:

    • Description: Utilize Django's built-in generic CBVs for common tasks like displaying a list of objects or handling form submissions.
    • Code Example:
      from django.views.generic import ListView
      
      class MyListView(ListView):
          model = MyModel
          template_name = 'my_model_list.html'
      
  4. Django CBV decorators and mixins:

    • Description: Use decorators and mixins with Class-Based Views to add additional behavior or restrictions.
    • Code Example:
      from django.contrib.auth.decorators import login_required
      from django.utils.decorators import method_decorator
      
      @method_decorator(login_required, name='dispatch')
      class MyProtectedView(View):
          # Your view logic here
      
  5. Using decorators with Django FBV:

    • Description: Apply decorators to Function-Based Views for scenarios such as authentication, caching, or custom functionality.
    • Code Example:
      from django.contrib.auth.decorators import login_required
      
      @login_required
      def my_protected_view(request):
          # Your view logic here
      
  6. Django REST framework CBV examples:

    • Description: Use Class-Based Views in Django REST framework for building API views with features like serializers and authentication.
    • Code Example:
      from rest_framework.views import APIView
      from rest_framework.response import Response
      
      class MyAPIView(APIView):
          def get(self, request):
              # Your API logic here
              return Response({"message": "Hello, this is a CBV for API"})
      
  7. Django FBV and CBV routing and URL patterns:

    • Description: Define URL patterns and routing for both FBVs and CBVs in Django's urls.py file.
    • Code Example:
      from django.urls import path
      from .views import my_view, MyClassBasedView
      
      urlpatterns = [
          path('fbv/', my_view, name='fbv_example'),
          path('cbv/', MyClassBasedView.as_view(), name='cbv_example'),
      ]