美文网首页
django_自定义用户模型

django_自定义用户模型

作者: 魔童转世 | 来源:发表于2018-08-04 22:34 被阅读0次

先来喷下简书的markdown的预览模式,整了我2小时,百度、google都没有找到怎么把markdown预览模式打开,后来不小心发现有文字的文档是打不开markdown的,俺也是第一次用markdown 真心费劲,关键是简书也不提示

概要

1、用户自定义model
2、自定义manage
3、自定义认证

自定义用户model

这个很简单 首先需要集成类 BaseUserManager 剩下的和自己写model基本一样
在加上框架要求必须要重写的方法就 ok了,代码如下

注意 代码中的 objects = MyUserManager() 好多文章没有解释 其实这个事指定model的管理类,如果不指定系统会调用原有的manager,系统会报错

第二个注意的问题就是is_staff 代表用户当前的用户是否有权限进入管理后台

需要在项目的setting里添加 AUTH_USER_MODEL ="项目名称.molde类名",不需要指定是哪个model,因为系统会自动的找到app目录下的model

class MyUser(AbstractBaseUser): # 定义自己的用户表
    wx_id = models.CharField(max_length=32,unique=True,verbose_name="微信ID")
    phone = models.CharField(max_length=32, verbose_name="手机号")
    is_active = models.BooleanField(default=True,verbose_name='是否启用')
    USERNAME_FIELD = 'phone'    # 定义使用哪个字段作为用户名来登录
    REQUIRED_FIELDS = ['wx_id'] # 不能为空的字段
    group = models.ManyToOneRel(Group,on_delete=models.CASCADE,field_name=Group,to=Group)
    class Meta:
        verbose_name = '用户'
        verbose_name_plural='用户'


    def get_full_name(self):
        # The user is identified by their email address
        return self.phone

    def get_short_name(self):
        # The user is identified by their email address
        return self.phone

    def __str__(self):              # __unicode__ on Python 2
        return self.phone

    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True

    @property
    def is_staff(self):
        "Is the user a member of staff?"
        # 用户是否可以进入站点
        return True

    objects = MyUserManager()

自定义manage

需要重写2个方法

class MyUserManager(BaseUserManager):   # 定义创建登录用户和超级用户时需要的字段
    def create_user(self, phone, wx_id, password=None):
        """
        Creates and saves a User with the given email, date of
        birth and password.
        """
        if not phone:
            raise ValueError('Users must have an phone ')

        user = self.model(
            phone=phone,
            wx_id = wx_id
        )

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, phone, wx_id, password):
        """
        Creates and saves a superuser with the given email, date of
        birth and password.
        """
        user = self.create_user(
            phone=phone,
            wx_id=wx_id
        )
        user.set_password(password)
        user.save(using=self._db)
        return user

自定义认证

没啥好说的直接上代码

from django.contrib.auth.backends import ModelBackend, UserModel

from forum.models import MyUser


class SettingsBackend:
    """
    Authenticate against the settings ADMIN_LOGIN and ADMIN_PASSWORD.

    Use the login name and a hash of the password. For example:

    ADMIN_LOGIN = 'admin'
    ADMIN_PASSWORD = 'pbkdf2_sha256$30000$Vo0VlMnkR4Bk$qEvtdyZRWTcOsCnI/oQ7fVOu1XAURIZYoOZ3iq8Dr4M='
    """

    def authenticate(self, request, username=None, password=None, **kwargs):
        if username is None:
            print("00")
            raise Exception('username 不能为空')
        else:
            try:
                user = MyUser.objects.get(phone=username)

            except MyUser.DoesNotExist:
                raise Exception("用户名密码不正确")
            if user.check_password(password) and self.user_can_authenticate(user):
                return user




    def get_user(self, user_id):
        try:
            user = UserModel._default_manager.get(pk=user_id)
        except UserModel.DoesNotExist:
            return None
        return user if self.user_can_authenticate(user) else None

    def user_can_authenticate(self, user):
        """
        Reject users with is_active=False. Custom user models that don't have
        that attribute are allowed.
        """
        is_active = getattr(user, 'is_active', None)
        return is_active or is_active is None

相关文章

网友评论

      本文标题:django_自定义用户模型

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