美文网首页
自定义用户认证(手机|用户名)

自定义用户认证(手机|用户名)

作者: 爱修仙的道友 | 来源:发表于2019-04-28 18:23 被阅读0次
  • 自定义用户模型
# 自定义用户模型
from django.db import models
from django.contrib.auth.models import AbstractUser


class UserProfile(AbstractUser):
    """
    新增字段
    """
    # null=True,blank=True, 用户注册时只提供了手机号,所以需要为空
    name = models.CharField(max_length=30,null=True,blank=True,verbose_name="姓名")
    birthday = models.DateField(null=True,blank=True,verbose_name="出生年月")
    mobile = models.CharField(max_length=11,verbose_name="电话")
    gender = models.CharField(max_length=6,choices=(("male","男"),("female","女")),default="female",verbose_name="性别")
    email = models.CharField(max_length=100,null=True,blank=True,verbose_name="邮箱")
    create_time = models.DateTimeField("创建时间", auto_now_add=True)
    update_time = models.DateTimeField("更新时间", auto_now=True)

    class Meta:
        db_table = "tb_users"
        verbose_name = "用户"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name

  • 声明用户模型
# 替换用户模型
AUTH_USER_MODEL = "users.UserProfile"
  • 视图
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q

User = get_user_model()

class CustomBackend(ModelBackend):
    """自定义用户验证"""

    def authenticate(self, request, username=None, password=None, **kwargs):
        # if username is None:
        #     username = kwargs.get(UserModel.USERNAME_FIELD)
        try:
            user = User.objects.get(Q(username=username)|Q(mobile=username))
        except User.DoesNotExist:
            # Run the default password hasher once to reduce the timing
            # difference between an existing and a nonexistent user (#20760).
            User().set_password(password)
        else:
            if user.check_password(password) and self.user_can_authenticate(user):
                return user
  • 配置
AUTHENTICATION_BACKENDS = (
    'users.views.CustomBackend',
)

相关文章

网友评论

      本文标题:自定义用户认证(手机|用户名)

      本文链接:https://www.haomeiwen.com/subject/jbodnqtx.html