gpt4 book ai didi

python - 在 Django 中创建用户 : User, Staff, SuperUser

转载 作者:行者123 更新时间:2023-11-30 21:41:57 27 4
gpt4 key购买 nike

我想在 models.py 和前端用户中创建并保存具有给定用户名、密码、名字、姓氏和电子邮件的用户,例如简单用户、员工和 super 用户由于一些限制,可以选择是简单用户,员工还是 super 用户。这是我在 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).

最佳答案

您应该扩展抽象的 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,希望这对您有所帮助。

关于python - 在 Django 中创建用户 : User, Staff, SuperUser,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51144779/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com