CBV实现登陆
urls.py:
url(r'^home/', views.MyHome.as_view()),
views.py ,三种方式实现登陆校验:
导入模块:from django.utils.decorators import method_decorator
from django.utils.decorators import method_decorator def login(request): if request.method == 'POST': username = request.POST.get('username') pwd = request.POST.get('pwd') if username == 'jason' and pwd == '123': request.session['name'] = 'jason' return redirect('/home/') return render(request,'login.html') from functools import wraps def login_auth(func): @wraps(func) def inner(request,*args,**kwargs): if request.session.get('name'): return func(request,*args,**kwargs) return redirect('/login/') return inner # @method_decorator(login_auth,name='get') # 第二种 name参数必须指定 class MyHome(View): # @method_decorator(login_auth) # 第三种 get和post都会被装饰 def dispatch(self, request, *args, **kwargs): super().dispatch(request,*args,**kwargs) # @method_decorator(login_auth) # 第一种 只校验一个 def get(self,request): return HttpResponse('get') def post(self,request): return HttpResponse('post')