您好,欢迎来到华佗小知识。
搜索
您的当前位置:首页django views的FBV和CBV的使用方式

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。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- huatuo0.cn 版权所有 湘ICP备2023017654号-2

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务