django.contrib.auth中的authenticate()|login()|logout()函数使用。
验证|登录|注销 函数
authenticate()--登录认证:
接受两个参数,用户名|username 密码|password
合法的情况下返回一个User对象。不合法,返回None。
用is not None else 判断是否验证成功.
语法:user=auth.authenticate(username=name,password=pwd)
login()--用户登录:
接受两个参数request对象和一个User对象
并自动保存session与cookie
语法:auth.login(request,user)
logout()--注销用户:
它接受一个request对象并且没有返回值,所以,需要返回一个页面。
语法:auth.logout(request)
示例 登录认证+登录设置:
def login(request):
if request.method =='GET':
# get请求返回登录页面
return render(request,'login.html')
if request.method =='POST':
# post请求接受验证数据
uname = request.POST.get('uname')
upwd = request.POST.get('upwd')
user=auth.authenticate(username=uname,password=upwd)
if user is not None and user.is_active:
# 验证通过返回首页
auth.login(request,user) # session cookie
return render(request,'index.html')
else:
# 验证不通过返回登录页面提示信息
return render(request,'login.html',{'msg':'用户名或密码错误'})
示例 注销用户:
def logot(request):
# 注销当前用户并返回首页
auth.logout(request)
return render(request,'index.html')