Django(补充CBV,FBV)

我们常用的都是FBV模式,就是url对应views.py中的函数

CBV模式:url------类

=====================

CBV实现过程:

浏览器通过url先执行Login类中的dispatch函数(分发器),dispatch会调用get/post方法
---------urls.py path('xxx',views.Login.as_view()) ---------views.py from django import views class Login(views.View): #继承于views.View类 def dispatch(self, request, *args, **kwargs): #这个函数作用类似于装饰器
#if request.method=="GET":
     # return HttpResponse("get方式") ret
=super(Login,self).dispatch(request,*args,**kwargs) #重写dispatch方法,相当于执行get/post方法(关键看传来的是那种请求方式,如果是get请求方式,就执行get方法) print(11111) return ret def get(self,request,*args,**kwargs): print("gettttttttt") return render(request,"login.html") def post(self,req,*args,**kwargs): user=req.POST.get("username") pwd=req.POST.get("password") rep=redirect("/index") rep.set_cookie("username",user) rep.set_cookie("password",pwd) return rep

POST/GET请求方式不同:

浏览器默认的方式是get形式

views.py
def login(req):
  return
render(req,"index.html",{"msg":""}) //第一次请求时,会返回一个空的字符串,因为是get请求

猜你喜欢

转载自www.cnblogs.com/gaoyukun/p/9064779.html