我对 Django 并不陌生,但通过从事这个项目,我正在积累经验。我使用 Django 4.2。我为用户创建了一个模型并运行了迁移。我尝试创建超级用户,但收到错误“电子邮件不是有效的 UUID 字段”。我知道“电子邮件”被传递到“UUID”字段,但我指定了 ID 字段,因此操作存在问题,但我似乎不明白在哪里。
这是我的
models.py
文件
import uuid
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.core.exceptions import FieldError
class UserManager(BaseUserManager):
def create_user(self, email, username, password, **kwargs):
if not email:
raise ValueError('Email must be given!')
kwargs.setdefault('is_active', True)
kwargs.setdefault('is_superuser', False)
email = self.normalize_email(email)
user = self.model(email, username, **kwargs)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password, **kwargs):
if not email:
raise ValueError('Email must be given!')
kwargs.setdefault('is_active', True)
kwargs.setdefault('is_superuser', True)
email = self.normalize_email(email)
superuser = self.model(email, **kwargs)
superuser.set_password(password)
superuser.save(using=self._db)
return superuser
class UserAccount(AbstractBaseUser, PermissionsMixin):
id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True)
email = models.CharField(max_length=250, unique=True, null=False)
username = models.CharField(max_length=250, unique=True, null=False)
password = models.CharField(max_length=200, null=False)
is_active = models.BooleanField(default=False)
is_verified = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
created_time = models.DateTimeField(auto_now_add=True, null=False)
last_login = models.DateTimeField(auto_now=True)
class Meta:
unique_together = ['id', 'email', 'username']
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = UserManager()
def __str__(self) -> str:
return super().__str__(self.email)
def has_perms(self, perm, obj=None):
return self.is_superuser
def get_full_name(self) -> str:
return self.username
def has_module_perms(self, app_label):
return True
我运行的命令是:
py manage.py makemigrations
、py manage.py migrate
、py manage.py createsuperuser
然后我收到此错误:
CommandError: “[email protected]” is not a valid UUID.
我已经查看了我的模型,但尚未发现任何问题。 我已尝试重新创建模型,但仍然遇到同样的问题。
有人可以帮忙吗?
按照以下步骤操作:
migrations
的 user_app
python manage.py makemigrations your_app_name
python manage.py migrate
python manage.py createsuperuser
注意 - 我认为它会引发错误,因为您在用户模型中添加了一些数据,然后在添加
Id
字段后自动生成 UUID