一、FBV
FBV(function base views) 就是在视图里使用函数处理请求,也是我们最开始接触和使用的方式。
urls.py
1
2
3
4
|
urlpatterns
=
[
url(r
'^admin/'
, admin.site.urls),
url(r
'^login/$'
, account.login),
]
|
views.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
# 登录验证
def
login(request):
message
=
""
if
request.method
=
=
"POST"
:
user
=
request.POST.get(
'username'
)
pwd
=
request.POST.get(
'password'
)
c
=
Administrator.objects.
filter
(username
=
user, password
=
pwd).count()
if
c:
request.session[
'is_login'
]
=
True
request.session[
'username'
]
=
user
return
redirect(
'/index.html'
)
else
:
message
=
"用户名或密码错误"
return
render(request,
'login.html'
, {
'msg'
: message})
|
说白了,FBV就是在views.py文件中定义函数来处理用户请求,函数中再定义如果是GET请求怎么处理,POST请求怎么处理,等等!
二、CBV
CBV(class base views) 就是在视图里使用类处理请求。
urls.py
1
2
3
4
|
urlpatterns
=
[
url(r
'^admin/'
, admin.site.urls),
url(r
'^login/$'
, account.Login.as_view()),
]
|
views.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
from
django
import
views
from
django.utils.decorators
import
method_decorator
class
Login(views.View):
def
get(
self
, request,
*
args,
*
*
kwagrs):
return
render(request,
'login.html'
)
def
post(
self
, request,
*
args,
*
*
kwagrs):
user
=
request.POST.get(
'username'
)
pwd
=
request.POST.get(
'password'
)
c
=
Administrator.objects.
filter
(username
=
user, password
=
pwd).count()
if
c:
request.session[
'is_login'
]
=
True
request.session[
'username'
]
=
user
return
redirect(
'/index.html'
)
else
:
message
=
"用户名或密码错误"
return
render(request,
'login.html'
, {
'msg'
: message})
|
当我们使用CBV方式时,首先要注意urls.py文件中要写成“类名.as_view()”方式映射,其次在类中我们定义的get/post方法这些方法的名字不是我们自己定义的,而是按照固定样式,View类中支持以下方法:
1
|
http_method_names
=
[
'get'
,
'post'
,
'put'
,
'patch'
,
'delete'
,
'head'
,
'options'
,
'trace'
]
|
当我们发送GET请求时,类自动将GET请求转到get方法去处理,其他请求同理!
本文转自戴柏阳的博客博客51CTO博客,原文链接http://blog.51cto.com/daibaiyang119/1976717如需转载请自行联系原作者
daibaiyang119