码迷,mamicode.com
首页 > 其他好文 > 详细

django 的用户验证及登录状态保持

时间:2018-06-01 21:09:18      阅读:1539      评论:0      收藏:0      [点我收藏+]

标签:登录验证   strong   rom   import   cts   username   传递   pre   入参   

一、用户验证功能

  Django自带用户验证及登录功能,引入模块为:

from django.contrib.auth import authenticate

  其中方法authenticate()的接收参数为:

def authenticate(request=None, **credentials):

  传入参数:

user = authenticate(username=login_user, password=login_password)

  authenticate方法自动在数据库中匹配、验证,但是不能实现邮箱登录的验证,需要对该方法重写,导入模块:

from django.contrib.auth.backends import ModelBackend

  创建重写类:

class ChongxieAuthenticate(ModelBackend):
def authenticate(self, username=None, password=None, **kwargs):
try:
user = UserProfile.objects.get(Q(username=username) | Q(email=username))
if user.check_password(password):
return user
else:
return None
except Exception as e:
return None

  如果用户名或邮箱、密码验证通过,则会将该对象传递给user,如果为通过,传回None

二、登录状态保持

  Django自带的login()方法可实现用户登录状态的保持,引入模块:

from django.contrib.auth import login

  如果登录验证通过,使用:

login(request, user)

  使用该方法后,会在服务器端的session中生成_auth_user_id和_auth_user_backend两个键值,并发到客户端作为cookie,前端页面可通过{% if request.user.is_authenticated %}判断是否登录,来实现登录状态的保持功能。

 

django 的用户验证及登录状态保持

标签:登录验证   strong   rom   import   cts   username   传递   pre   入参   

原文地址:https://www.cnblogs.com/wendaobiancheng/p/9123382.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!