Django 路由及视图函数补充 CBV 实现

二、CBV & FBV
	CBV:指视图函数为类。
	FBV:指视图函数为函数类型。
	web框架的实质就是通过url-找到->函数,然后执行视图函数,模版渲染,把字符串返回给浏览器!
	这一段时间以来的操作,都是用的FBV类型来实现url ----> 函数。
	现在聊聊CBV的方式,以登录login举例。(全部是固定写法,不理解就记住吧!)
		
		1、视图函数views中:
			from django.views import View  #先导入模块
			
			class Login(View): #定义一个类,继承父类View  -------> 没错,就是导入的模块
				"""
				- 在类内定义不同的http方法,我们可以点进View中去查看,官方给的方法如下:
				- http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']
				- 对于这些方法,我们常用的只有四个,同时这四个分别代表不同的操作:
					get    查
					post   创建
					put    更新
					delete 删除
				"""
				#在View父类中,我们看源码发现有个 dispatch 函数,这个函数是用来执行类内自定义的方法的。
				#所以对于这个函数,我们可以重写,以增加我们需要的功能!当然如果不需要的话,那就不要重写。
				
				def dispatch(self, request, *args, **kwargs):
					print("before")
					obj = super(Login,self).dispatch(self, request, *args, **kwargs)
					print("after")
					return obj
				#不管定义什么方法,都需要写一个形参request,用于接收浏览器发送过来的请求信息.
				def get(self,request):  
					return render(request,"login.html")
				
				def post(self,request):
					print(request.POST.get("user"))  #有没有获取到数据
					return HttpResponse("login.POST")
		
		2、urls.py路由系统文件中:
			"""注意后边函数,也是固定的写法:模块.类名.as_view()"""
			url(r'^login.html$', views.Login.as_view()),
		
		3、模版文件login.html:#form 表单提交只有两种方式:get和POST
			<!DOCTYPE html>
			<html lang="en">
			<head>
				<meta charset="UTF-8">
				<title>Title</title>
			</head>
			<body>
			<form method="POST" action="/login.html">
				<input name="user" type="text">
				<input type="submit" value="提交">
			</form>
			</body>
			</html>

  

posted @ 2017-07-22 18:20  细雨蓝枫  阅读(110)  评论(0编辑  收藏  举报