Django Tutorial
Django Create A Complete Project
Django Template
Django Database Query
Django Form
Django Authentication and Permission Management
Django unittest
Django Advanced
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:
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:
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)
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:
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)
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:
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'), ]
.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:
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.
Django FBV example code:
from django.shortcuts import render from django.http import HttpResponse def my_view(request): return HttpResponse("Hello, this is a Function-Based View!")
Mixins in Django Class-Based Views:
from django.contrib.auth.mixins import LoginRequiredMixin class MyView(LoginRequiredMixin, View): # Your view logic here
Generic Class-Based Views in Django:
from django.views.generic import ListView class MyListView(ListView): model = MyModel template_name = 'my_model_list.html'
Django CBV decorators and mixins:
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
Using decorators with Django FBV:
from django.contrib.auth.decorators import login_required @login_required def my_protected_view(request): # Your view logic here
Django REST framework CBV examples:
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"})
Django FBV and CBV routing and URL patterns:
urls.py
file.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'), ]