Django练习——用户管理系统——补充知识点
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django练习——用户管理系统——补充知识点相关的知识,希望对你有一定的参考价值。
补充知识点:
1.FBV 和 CBV
views.py # 方法一:FBV def login(request): if request.method == "POST": user = request.POST.get("user") pwd = request.POST.get("pwd") c = models.Administrator.objects.filter(username=user,password=pwd).count() print(c) if c: #设置session中存储的数据 request.session["is_login"] = True request.session["username"] = user #尤其注意跳转到哪个页面!!! return render(request,"index.html",{"username":user}) else: msg = "用户名或密码错误" return redirect("/login.html",{"msg":msg}) return render(request,"login.html")
urs.py
# url(r‘^login.html$‘, views.login),
cbv:
#CBV from django import views class Login(views.View): def get(self,request,*args,**kwargs): return render(request, "login.html") def post(self,request,*args,**kwargs): user = request.POST.get("user") pwd = request.POST.get("pwd") c = models.Administrator.objects.filter(username=user, password=pwd).count() print(c) if c: #设置session中存储的数据 request.session["is_login"] = True request.session["username"] = user #尤其注意跳转到哪个页面!!! return render(request,"index.html",{"username":user}) else: msg = "用户名或密码错误" return redirect("/login.html",{"msg":msg})
urs.py
url(r‘^login.html$‘, views.Login.as_view()),#以类的方式进行创建
2.类中用装饰器
方法一:自定义装饰器
from django import views from django.utils.decorators import method_decorator#1.引入库 #2.定义装饰器函数 def outer(func): def inner(request,*args,**kwargs): print(request.method) return func(request,*args,**kwargs) return inner class Login(views.View): #3.使用装饰器 @method_decorator(outer) def get(self,request,*args,**kwargs): return render(request, "login.html")
方法二:自定义dispatch方法,同时继承父类该方法,等同于装饰器
from django import views class Login(views.View): #1.先执行自定义的dispatch方法 def dispatch(self, request, *args, **kwargs): print(11111) if request.method == "GET": return HttpResponse("ok") #2.再调用父类中的dispatch方法,dispatch方法类似路由分发 ret = super(Login,self).dispatch(request, *args, **kwargs) print(22222) return ret def get(self,request,*args,**kwargs): return render(request, "login.html") def post(self,request,*args,**kwargs): user = request.POST.get("user") pwd = request.POST.get("pwd") c = models.Administrator.objects.filter(username=user, password=pwd).count() print(c) if c: #设置session中存储的数据 request.session["is_login"] = True request.session["username"] = user #尤其注意跳转到哪个页面!!! return render(request,"index.html",{"username":user}) else: msg = "用户名或密码错误" return redirect("/login.html",{"msg":msg})
以上是关于Django练习——用户管理系统——补充知识点的主要内容,如果未能解决你的问题,请参考以下文章