标签: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方法,最终出现了想要的效果!
标签:lse com from lin http action isp image form表单
原文地址:https://www.cnblogs.com/changwenjun-666/p/11000206.html