码迷,mamicode.com
首页 > 其他好文 > 详细

django 的CBV

时间:2019-06-10 21:17:38      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:lse   com   from   lin   http   action   isp   image   form表单   

CBV:基于函数的视图

1、在路由层

url(r‘^mycls/‘,views.MyCls.as_view())

 

2、在视图层

from django.views import View
class MyCls(View):
    def get(self,request):
        return render(request,‘get.html‘)
    def post(self,request):
        return HttpResponse(‘post‘)

  

3、get.html 页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<link rel="stylesheet" href="/static/bootstrap-3.3.7/css/bootstrap.min.css">
<script src="/static/bootstrap-3.3.7/js/bootstrap.min.js"></script>
</head>
<body>

<form action="" method="post">{% csrf_token %}
<input type="submit" >
</form>

</body>
</html>
添加一个form表单,请求方式改为post.
django项目里的settings 下的 MIDDLEWARE 下的 csrf 未被注释,因此加上了 {% csrf_token %}

  

<input type="submit" > </form> </body> </html> 添加一个form 表单,其请求方式改为 post

4、在浏览器输入 127.0.0.1:8000/mycls  后,html页面出现了如下情况:

技术图片      点击按钮后出现:               技术图片

 

问题:

1、views.MyCls.as_view()  是什么?

其本质是路由对应视图函数的内存地址,当输入对应路由后,会调用该函数,FBV的本质也是一样

2、为什么仅仅定义两个方法,就能生成如此效果?

解释:

2.1  as_view 并不是MyCla 的内部所定义的方法,是从父类View处继承而来

2.2   查看as_view 内部源代码:如下

技术图片

 

2.3  ad_view() 的返回值是 view ,再次查看 view 的源代码:如下

技术图片

 

2.4  同样发现类MyCal 自身不存在该方法,依然是继承父类的 dispatch方法,查看源代码,如下:

技术图片

此处的 http_method_names属性值为: 

http_method_names = [‘get‘, ‘post‘, ‘put‘, ‘patch‘, ‘delete‘, ‘head‘, ‘options‘, ‘trace‘]

因此,返回值恰好是自己定义的get方法和post方法,最终出现了想要的效果!

django 的CBV

标签:lse   com   from   lin   http   action   isp   image   form表单   

原文地址:https://www.cnblogs.com/changwenjun-666/p/11000206.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!