zoukankan      html  css  js  c++  java
  • django 的用户验证及登录状态保持

    一、用户验证功能

      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 %}判断是否登录,来实现登录状态的保持功能。

  • 相关阅读:
    遇到容易忘记的问题(二)
    遇到容易忘记的问题(三)
    遇到容易忘记的问题(一)
    UC浏览器input文本框输入文字回车键自动提交
    弹框在当前屏幕完全居中的方法
    遇到的浏览器问题总结
    HTML常用的特殊符号&前端使用的标点符号
    小程序里的页面跳转
    移除所有子视图
    UIView用户事件响应
  • 原文地址:https://www.cnblogs.com/wendaobiancheng/p/9123382.html
Copyright © 2011-2022 走看看