[Django] FBV and CBV
Sep 26, 2021
FBV (Function Based Views)
views.py
def login(request):
if request.method == “GET”:
...
if request.method == “POST”:
...
urls.py
urlpatterns = [
path(‘login/’, views.login),
]
CBV (Class Based Views)
views.py
class Login(View):
def get(self,request):
...
def post(self,request):
...
urls.py
urlpatterns = [
path(‘login/’, views.Login.as_view()),
]
FBV in comparison with CBV
- FBV use functions that we define ourselves, and use the request to judge different HTTP methods.
- CBV use classes that we define ourselves, and the class need to inherit View related object from Django. We can use functions in class to seperate HTTP methods.
- FBV could use in the case that the views is special, and almost not duplicated.
- CBV could avoid duplicate code block, and be more readable if the inheritance are not complicated.