在django中创建用户:user、staff、superuser

m0rkklqb  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(332)

我想创建和保存一个用户与给定的用户名,密码,名字,姓氏和电子邮件,如简单的用户,工作人员和超级用户 models.py 而在前端用户可以选择是简单用户、职员还是超级用户,因为有一些限制。这是我的密码 models.py . 在这段代码之后,我得到了一些系统检查错误。

class CustomUserManager(UserManager):

    def _create_user(self, username, email, password,**extra_fileds):
        if not username:
            raise ValueError('The given username must be set')
        email = self.normalize_email(email)
        username = self.model.normalize_username(username)
        user = self.model(username=username, email=email,**extra_fileds)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, username, email=None, password=None,**extra_fileds):
        extra_fields.setdefault('is_staff', False)
        extra_fields.setdefault('is_superuser', False)
        return self._create_user(username, email, password,**extra_fileds)

    def create_superuser(self, username, email, password,**extra_fileds):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', 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(username, email, password,**extra_fileds)

class CustomUser(AbstractUser):
    username = models.CharField(
        _('username'),
        max_length=150,
        unique=True,
        help_text=_('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'),
        # validators=[username_validator],
        error_messages={
            'unique': _("A user with that username already exists."),
        },
    )
    password = models.CharField(_('password'), max_length=128)
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=150, blank=True)
    email = models.EmailField(_('email address'), blank=True)
    is_staff = models.BooleanField(
        _('staff status'),
        default=False,
        help_text=_('Designates whether the user can log into this admin site.'),
    )
    is_active = models.BooleanField(
        _('active'),
        default=True,
        help_text=_(
            'Designates whether this user should be treated as active. '
            'Unselect this instead of deleting accounts.'
        ),
    )
    objects = CustomUserManager()

错误:

Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x10a7dd598>
Traceback (most recent call last):
  File "/Users/eLmaesTro/anaconda3/envs/djangoEnv/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper
    fn(*args,**kwargs)
  File "/Users/eLmaesTro/anaconda3/envs/djangoEnv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 121, in inner_run
    self.check(display_num_errors=True)
  File "/Users/eLmaesTro/anaconda3/envs/djangoEnv/lib/python3.6/site-packages/django/core/management/base.py", line 410, in check
    raise SystemCheckError(msg)
django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues:

错误:

auth.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'CustomUser.groups'.
        HINT: Add or change a related_name argument to the definition for 'User.groups' or 'CustomUser.groups'.
auth.User.user_permissions: (fields.E304) Reverse accessor for 'User.user_permissions' clashes with reverse accessor for 'CustomUser.user_permissions'.
        HINT: Add or change a related_name argument to the definition for 'User.user_permissions' or 'CustomUser.user_permissions'.
testapp.CustomUser.groups: (fields.E304) Reverse accessor for 'CustomUser.groups' clashes with reverse accessor for 'User.groups'.
        HINT: Add or change a related_name argument to the definition for 'CustomUser.groups' or 'User.groups'.
testapp.CustomUser.user_permissions: (fields.E304) Reverse accessor for 'CustomUser.user_permissions' clashes with reverse accessor for 'User.user_permissions'.
        HINT: Add or change a related_name argument to the definition for 'CustomUser.user_permissions' or 'User.user_permissions'.

System check identified 4 issues (0 silenced).
ljo96ir5

ljo96ir51#

您应该扩展abstractbaseuser并为用户创建新的模式,这里我可以为您提供我的代码作为示例

class UserManager(BaseUserManager):

def create_user(self, username, email, password):
    if not email:
        raise ValueError('Users must have an email address')

    elif not username:
        raise ValueError('Users must have an username')

    user = self.model(
        email=self.normalize_email(email),
        username=username,
    )

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

def create_superuser(self, username, email, password):
    user = self.create_user(
        email=email,
        username=username,
        password=password,
    )
    user.is_admin = True
    user.save(using=self._db)
    return user

class User(AbstractBaseUser):
email = models.EmailField(
    verbose_name='email address',
    max_length=255,
    unique=True,
)
username = models.CharField(
    verbose_name='username',
    max_length=30,
    unique=True,
)

phonenumber = PhoneNumberField(verbose_name="phonenumber",max_length=13,
                null=True,unique=True)
name = models.CharField(max_length=30, blank=True)

display_username = models.CharField(
    verbose_name='display_username',
    max_length=30,
    unique=True,null= True
)

is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = UserManager()

# REQUIRED_FIELDS = ['email',]

USERNAME_FIELD = 'email'

def get_full_name(self):
    return self.name

def get_short_name(self):
    return self.name

def __str__(self):
    return self.display_username

def has_perm(self, perm, obj=None):
    return True

def has_module_perms(self, app_label):
    return True

def get_absolute_url(self):
    return reverse('accounts:profile', kwargs={'username': self.username})

@property
def is_staff(self):
    return self.is_admin

在您的settings.py中

AUTH_USER_MODEL = 'accounts.User' #accounts is your app name

现在你可以编辑了 user 根据您的要求,希望这能对您有所帮助。

相关问题