Django Views Fbv Cbv
# Django Views β FBV vs CBV
**FBV (Function-Based Views)** are views that use functions to handle requests.
**CBV (Class-Based Views)** are views that use classes to handle requests.
### FBV
Function-based views have been used in previous chapters, where functions handle user requests. See the example below:
URL configuration:
## urls.py file
```python
urlpatterns = [
path("login/", views.login),
]
## views.py file
```python
from django.shortcuts import render, HttpResponse
def login(request):
if request.method == "GET":
return HttpResponse("GET method")
if request.method == "POST":
user = request.POST.get("user")
pwd = request.POST.get("pwd")
if user == "" and pwd == "123456":
return HttpResponse("POST method")
else:
return HttpResponse("POST method 1")
If we directly access http://127.0.0.1:8000/login/ in the browser, the output will be:
GET method
### CBV
Class-based views use classes to handle user requests. Different methods within the class can handle different requests, which greatly improves code readability.
The defined class must inherit from the parent class `View`, so you need to import it first:
```python
from django.views import View
Before executing the method corresponding to the request, the `dispatch` method is called first (executed before get/post/put... methods). The `dispatch()` method calls the appropriate method based on the request type.
In Django, URLs are typically assigned to callable functions, not classes. So how are class-based views implemented? This is mainly achieved through the static method `as_view()` provided by the parent class `View`. The `as_view` method serves as the external interface for class-based views. It returns a view function, and when called, the request is passed to the `dispatch` method, which then handles different requests by calling the appropriate methods.
URL configuration:
## urls.py file
```python
urlpatterns = [
path("login/", views.Login.as_view()),
]
## views.py file
```python
from django.shortcuts import render, HttpResponse
from django.views import View
class Login(View):
def get(self, request):
return HttpResponse("GET method")
def post(self, request):
user = request.POST.get("user")
pwd = request.POST.get("pwd")
if user == "" and pwd == "123456":
return HttpResponse("POST method")
else:
return HttpResponse("POST method 1")
If we directly access http://127.0.0.1:8000/login/ in the browser, the output will be:
GET method
YouTip