0
点赞
收藏
分享

微信扫一扫

Django中authenticate和login模块登录用户

小猪肥 2022-02-17 阅读 55

Django中authenticate和login模块

Django 提供内置的视图(view)函数用于处理登录和退出,Django提供两个函数来执行django.contrib.auth中的动作 : authenticate()和login()。

认证给出的用户名和密码,使用 authenticate() 函数。它接受两个参数,用户名 username 和 密码 password ,并在密码对给出的用户名合法的情况下返回一个 User 对象。 如果密码不合法,authenticate()返回None。

from django.contrib.auth import authenticate, login

user = authenticate(username='john', password='secret')
if user is not None:
  print("Correct!")
else:
  print("Invalid password.")

登录和验证

authenticate() 只是验证一个用户的证书而已。 而要登录一个用户,使用 login() 。该函数接受一个 HttpRequest 对象和一个 User 对象作为参数并使用Django的会话( session )框架把用户的ID保存在该会话中。

	username = request.POST.get('username')
	password = request.POST.get('pwd')

    # django内置认证来校验登录用户
    user = authenticate(username=username, password=password)
    if user is not None:
        if user.is_active:
            # 记住登录状态
            login(request, user)
            response = redirect('goods:index')
            return response
        else:
            return render(request, 'login.html', {'errmsg': '账户未激活'})
    else:
        return render(request, 'login.html', {'errmsg': '用户名或密码错误'})

登出

注销一个用户,在你的视图中使用django.contrib.auth.logout() 。 它接受一个HttpRequest对象并且没有返回值,所以,因为没有返回值,需要返回一个页面

from django.contrib.auth import logout
 
def logout_view(request):
  logout(request)
  return render(request, 'login.html')
举报

相关推荐

0 条评论