django 使用装饰器验证用户登陆
1 def checkLogin(func): 2 def wrapper(request,*args,**kwargs): 3 is_login=request.session.get('Is_Login',False) 4 if is_login: 5 return func(request,*args,**kwargs) #此处一定要有return,否则会报返回为空的错误. 6 else: 7 return redirect('/Index/') 8 return wrapper
login 模块
1 def login_user(request): 2 if request.method == 'POST': 3 form = LoginForm(request.POST) 4 if form.is_valid(): 5 all_data = form.clean() #获取post数据,例如 {'username': u'yang1', 'password': 111} 6 exist = User.objects.filter(username = all_data['Form_username'],password = all_data['Form_password']).first() 7 if exist: 8 request.session['Is_Login'] = True #设置session的随机字段值 9 request.session['username'] = exist.username #设置uname字段为登录用户 10 return redirect('/index/') 11 else: 12 return HttpResponse("账户或密码错误") 13 else: 14 form = LoginForm() 15 return render(request, 'login.html', {'form': form}) 16 17 @checkLogin 18 def home(request): 19 username = request.session.get('uname', False) #获取登录用户名 20 return render(request, home.html', {'username': username}) #用户名渲染到前端页面