Django登录使用的技术和组件
登录
'''
获取用户所有的数据
每条数据请求的验证
成功之后获取所有正确的信息
失败则显示错误信息
'''
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#登陆页面管理 def login(request): if request.method == 'GET': return render(request,'login.html') elif request.method == 'POST': obj = FM(request.POST) sucst = obj.is_valid() if sucst: username = obj.cleaned_data['username'] password = obj.cleaned_data['password'] #添加注册方法--往数据库中添加字段 # models.UserInfo.objects.create(**obj.cleaned_data) dic = models.UserInfo.objects.filter(username=username).first() # print(dic.username) if not dic: return render(request, 'login.html',{'usererrors':'此用户未注册'}) elif dic.password == password: request.session['username'] = username request.session['is_login'] = True return redirect('/index/') else: return render(request,'login.html',{'pswerrors':'密码错误'}) else: # print(obj.errors) return render(request, 'login.html', {'obj': obj})
session
'''
生产随机字符串
写到用户浏览器
保持在session中
依赖cookie
'''
session本身封装了上述功能
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
request.session['username'] = username request.session['is_login'] = True
session封装成装饰器进行用户验证
'''
获取用户登录字段状态
获取用户字段名称赋值username
查找用户所在组
通过组ID获取权限
'''
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#这个是做管理员与商务部人员双重验证,管理材料出入库:不是管理员或商务部人员则返回主页 def identity(fun): def verication(request,*args,**kwargs): if request.session.get('is_login',None): username = request.session.get('username') #print(username) groupid = models.UserInfo.objects.filter(username=username).first().usergroup_id #print(groupid) usergroup = models.UserGroup.objects.filter(id=groupid).first().groupname #print(usergroup) if usergroup == '管理员' or usergroup == '商务部': return fun(request,*args,**kwargs) else: return redirect('/index/') else: return redirect('/index/') return verication
用户退出
'''
清除session状态
'''
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
def logout(request): request.session.clear() return redirect('/login/')