自定义django用户模型的省略密码字段

时间:2019-03-11 12:20:21

标签: python django

我想拥有一个只有

的自定义Django用户模型
  

电子邮件ID,名字,姓氏和加入日期

字段。我不需要密码列,因为身份验证是通过Microsoft SAML进行的,因此不需要存储任何密码。我的用户模型如下:

from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import PermissionsMixin, 
                                       BaseUserManager, AbstractBaseUser
from django.utils.translation import ugettext_lazy as _


class UserManager(BaseUserManager):
    def _create_user(self, email, **extra_fields):
        if not email:
            raise ValueError('The Email must be set')
        email = self.normalize_email(email)
        user = self.model(email=email, extra_fields)
        user.save()

        return user

    def create_superuser(self, email, **extra_fields):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)
        extra_fields.setdefault('is_active', True)

        if extra_fields.get('is_staff') is not True:
            raise ValueError('Superuser must have is_staff=True.')
        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True.')
        return self._create_user(email, **extra_fields)


class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(_('email address'), unique=True)
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=30, blank=True)
    date_joined = models.DateTimeField(_('date joined'), auto_now_add=True)

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['first_name', 'last_name']

    class Meta:
        verbose_name = _('user')
        verbose_name_plural = _('users')

    def get_full_name(self):
        full_name = f'{self.first_name} {self.last_name}'
        return full_name.strip()

但是,当我运行迁移时,我也可以在用户表中看到密码字段。我在做什么错了?

2 个答案:

答案 0 :(得分:4)

我无法发表评论,但可以作为答复,但您可以使用'set_unusable_password'来跳过密码字段。

https://docs.djangoproject.com/en/2.0/ref/contrib/auth/#django.contrib.auth.models.User.set_unusable_password

赞:

class UserManager(BaseUserManager):
    def _create_user(self, email, **extra_fields):
        if not email:
            raise ValueError('The Email must be set')
        email = self.normalize_email(email)
        user = self.model(email=email, extra_fields)
        user.set_unusable_password()
        user.save()

        return user

答案 1 :(得分:1)

这是一个hack。 您可以删除此字段 ('password', models.CharField(max_length=128, verbose_name='password')), 从迁移文件中。但是,这是不可扩展的。