django views的FBV和CBV的使用方式

setting中注释:

#'django.middleware.csrf.CsrfViewMiddleware',

FBV模式:

function base views

url.py:

re_path(r'fbv', views.fbv)

views.py:

def fbv(request):
    return render(request, 'fbv.html', {'method': request.method})

templates文件夹下:

创建fbv.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>fbv</title>
</head>
<body>
<h3>{{method}}</h3>
<form action="fbv" method="post">
    <input type="submit">
</form>
</form>
</body>
</html>

运行环境:python manage.py runsrver 0.0.0.0:8080

浏览器进入默认get方式如下图:

点击提交按钮,通过form表单实现post请求,如下图:

CBV模式:

class base views

 

url.py:

re_path(r'cbv$', views.CBV.as_view()),

views.py:

class CBV(View):
    def get(self,request):
        return render(request, 'cbv.html', {'method': 'CBV.GET'})

    def post(self,request):
        return HttpResponse('<h3>CBV.POST</h3>')

cbv.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>cbv</title>
</head>
<body>
<h3>{{method}}</h3>
<form action="cbv" method="post">
    <input type="submit">
</form>
</form>
</body>
</html>

自动加载django。

浏览器打开:

点击提交按钮,通过form表单实现post的工作:

CBV的动作是:

http请求 -  url - views.CBV.as_views() - 进入View类 - dispatch方法读取method - 执行CBV类中的对应的方法。

会通过自己继承的View类中,自动找到method,执行对应的类函数,不需要人工判断是GET还是POST。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值