Django Views - FBV and CBV
FBV(function base views) A function-based view is one that uses a function in the view to handle requests.
CBV(class base views) A class-based view is one that uses a class in the view to handle requests.
FBV
Function-based views have actually been used throughout the previous chapters, using functions to handle user requests; see the following example:
Route configuration:
urls.py file
urlpatterns
=
[
path
(
"login/"
,
views.
login
)
,
]
views.py file
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
==
"runoob"
and
pwd
==
"123456"
:
return
HttpResponse
(
"POST method"
)
else
:
return
HttpResponse
(
"POST method 1"
)
If we directly visit http://127.0.0.1:8000/login/ in the browser, the output is:
GET 方法
CBV
A class-based view uses a class to handle user requests; different requests can be handled with different methods in the class, which greatly improves code readability.
The defined class must inherit from the parent class View, so you need to import the library first:
from django.views import View
Before executing the method corresponding to a request, the dispatch method is executed first (before the get/post/put... methods); the dispatch() method calls the corresponding method to handle it based on the request.
Actually, as we learned earlier, Django's url assigns a request to a callable function, not a class, so how are class-based views implemented? Mainly through a static method as_view() provided by the parent class View; the as_view method is the external interface of the class-based view, which returns a view function; when called, the request is passed to the dispatch method, and the dispatch method then handles different methods according to different requests.
Route configuration:
urls.py file
urlpatterns
=
[
path
(
"login/"
,
views.
Login
.
as_view
(
)
)
,
]
views.py file
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
==
"runoob"
and
pwd
==
"123456"
:
return
HttpResponse
(
"POST method"
)
else
:
return
HttpResponse
(
"POST method 1"
)
If we directly visit http://127.0.0.1:8000/login/ in the browser, the output is:
GET 方法