我尝试创建一个继承自 drf 中的 AbstractBaseUser 的 CustomUser 模型,但是当我尝试创建一个新的超级用户来登录管理站点时,它不起作用。它显示超级用户创建成功,但是当运行manage.py shell并尝试获取我刚刚创建的确切用户时,它显然不存在。
我的自定义用户模型:
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, Group, Permission
from .managers import UserManager
from django.utils.translation import gettext_lazy as lz
import uuid
import base64
ITEM = (
("pastries", 'pastries'),
("rentals",'rentals'),
("music", 'music'),
("help", 'help')
)
class CustomUser(AbstractBaseUser, PermissionsMixin):
objects = UserManager()
id = models.CharField(max_length=12, unique=True, primary_key=True, editable=False)
username = models.CharField(max_length=55, unique=True)
email = models.EmailField(verbose_name=lz('email address'), unique=True, max_length=255)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_superuser = models.BooleanField(default=False)
last_login = models.DateTimeField(null=True, blank=True)
is_verified = models.BooleanField(default=False)
date_joined = models.DateTimeField(auto_now_add=True)
groups = models.ManyToManyField(
Group,
related_name='accounts_user_groups',
blank=True,
help_text="the groups this user belongs to",
verbose_name=lz('groups')
)
user_permissions = models.ManyToManyField(
Permission,
related_name='accounts_user_permissions',
blank=True,
help_text="permissions for this user",
verbose_name=lz('user permissions')
)
USERNAME_FIELD = "email"
REQUIRED_FIELDS = ["username"]
def __str__(self) -> str:
return self.email
@property
def get_full_name(self):
return f'{self.first_name} {self.last_name}'
def save(self, *args, **kwargs):
if not self.id:
# Generate a shorter base64-encoded UUID
hex_string = uuid.uuid4().hex
bytes_data = bytes.fromhex(hex_string)
data = base64.urlsafe_b64encode(bytes_data).decode('ascii')[:12]
self.id = data.replace("-","").replace("_", "")
super().save(*args, **kwargs)
我的 manager.py 文件
from django.contrib.auth.models import BaseUserManager
from typing import Any
from django.core.validators import validate_email
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as lz
class UserManager(BaseUserManager):
def email_validator(self, email):
try:
validate_email(email)
except ValidationError:
raise ValueError(lz("enter a valid email address"))
def create_user(self, email, username, password, **extra_fields):
if email:
email = self.normalize_email(email)
self.email_validator(email)
else:
raise ValidationError(lz("an email address is required"))
if not username:
raise ValidationError(lz("a username is required"))
user = self.model(self, email, username, password, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, username, password, **extra_fields):
extra_fields.setdefault("is_staff", True)
extra_fields.setdefault("is_superuser", True)
if extra_fields.get("is_staff") is not True:
raise ValueError(lz("is staff must be true for admin user"))
if extra_fields.get("is_superuser") is not True:
raise ValueError(lz("is superuser must be true for admin user"))
user = self.create_user(email, username, password, **extra_fields)
user.save(using=self._db)
return user
遵循了我在 drf 文档上看到的所有资源,仍然没有解决方案 默认情况下,is_staff 和 is_superuser 设置为 true,但是仍然找不到它,或者更确切地说,没有创建它......
在您的创建_用户中尝试此操作,从模型实例化中删除“self”
user = self.model(
email=email,
username=username,
**extra_fields`enter code here`
)
user.set_password(password)
user.save(using=self._db)
return user
然后删除您的迁移 python 管理.py makemigrations python 管理.py 迁移 python 管理.py
createsuperuser
希望这有帮助