Categories: djangopython

django中FBV和CBV的用法

一、FBV

FBV(function base views) 就是在视图里使用函数处理请求。

看代码:

urls.py

1
2
3
4
5
6
7
8
from django.conf.urls import url, include
# from django.contrib import admin
from mytest import views
urlpatterns = [
# url(r‘^admin/‘, admin.site.urls),
url(r‘^index/‘, views.index),
]

views.py

1
2
3
4
5
6
7
8
9
from django.shortcuts import render
def index(req):
if req.method == ‘POST‘:
print(‘method is :‘ + req.method)
elif req.method == ‘GET‘:
print(‘method is :‘ + req.method)
return render(req, ‘index.html‘)

注意此处定义的是函数【def index(req):】

index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
</head>
<body>
<form action="" method="post">
<input type="text" name="A" />
<input type="submit" name="b" value="提交" />
</form>
</body>
</html>

上面就是FBV的使用。

二、CBV

CBV(class base views) 就是在视图里使用类处理请求。

将上述代码中的urls.py 修改为如下:

1
2
3
4
5
6
from mytest import views
urlpatterns = [
# url(r‘^index/‘, views.index),
url(r‘^index/‘, views.Index.as_view()),
]

注:url(r‘^index/‘, views.Index.as_view()),  是固定用法。

将上述代码中的views.py 修改为如下:

1
2
3
4
5
6
7
8
9
10
11
from django.views import View
class Index(View):
def get(self, req):
print(‘method is :‘ + req.method)
return render(req, ‘index.html‘)
def post(self, req):
print(‘method is :‘ + req.method)
return render(req, ‘index.html‘)

注:类要继承 View ,类中函数名必须小写。

另外CBA中,前端的请求是get就使用函数get中的方法,前端的请求是post就使用函数post中的方法。

 

 

Kai

Share
Published by
Kai

Recent Posts

VC 6.0 挂服务 提示503

我们有一台VC 6.0的服务挂…

2 周 ago

零成本grass挖矿教程

最近发现个新币,还没上交易所,…

3 周 ago

Windows Server 2025 的AD架构版本

   Windows 2025…

3 周 ago

【项目】跨数据中心(跨站点)Exchange Server 2013恢复/高可用

今年换到一家乙方公司了,主要工…

3 周 ago

主域挂了怎么办?

假设在极端情况下,没有备份的前…

1 月 ago

为什么在AD管理中只能看到3个操作主机?

我们在日常的Windows域管…

1 月 ago