0

我正在尝试创建一个自定义用户模型,当我运行 python manage.py createsuperuser 时,它会提示输入用户名,然后是密码,并确认密码,然后当我按下回车键时,我收到此错误

django.db.utils.IntegrityError: UNIQUE constraint failed: accounts_user.email

模型.py:

class UserManager(BaseUserManager):
    def _create_user(self, username, password=None, **extra_fields):
        if not username:
            raise ValueError("User must have a username")
        if not username:
            raise ValueError("User must have a password")
        user = self.model(
            username=username
        )

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

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

    def create_superuser(self, username, password=None, **extra_fields):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_admin', True)
        return self._create_user(username, password, **extra_fields)


class User(AbstractBaseUser):
    username = models.CharField(max_length=255, unique=True)
    email = models.EmailField(max_length=255, unique=True)
    active = models.BooleanField(default=True)
    admin = models.BooleanField(default=False)
    staff = models.BooleanField(default=False)
    USERNAME_FIELD = "username"
    REQUIRED_FIELDS = []

    objects = UserManager()

    def __str__(self):
        return self.username

整个错误日志:

PS C:\Users\PC\Desktop\nitrofleet> python manage.py createsuperuser
Username: lol
Password: 
Password (again):
This password is too short. It must contain at least 8 characters.
This password is too common.
This password is entirely numeric.
Bypass password validation and create user anyway? [y/N]: y
Traceback (most recent call last):
  File "C:\Users\PC\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\PC\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute
    return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: UNIQUE constraint failed: accounts_user.email

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\PC\Desktop\nitrofleet\manage.py", line 22, in <module>
    main()
  File "C:\Users\PC\Desktop\nitrofleet\manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "C:\Users\PC\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line
    utility.execute()
  File "C:\Users\PC\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 413, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Users\PC\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Users\PC\AppData\Local\Programs\Python\Python310\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 79, in execute
    return super().execute(*args, **options)
  File "C:\Users\PC\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 398, in execute
    output = self.handle(*args, **options)
  File "C:\Users\PC\AppData\Local\Programs\Python\Python310\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 189, in handle
    self.UserModel._default_manager.db_manager(database).create_superuser(**user_data)
  File "C:\Users\PC\Desktop\nitrofleet\accounts\models.py", line 29, in create_superuser
    return self._create_user(username, password, **extra_fields)
  File "C:\Users\PC\Desktop\nitrofleet\accounts\models.py", line 18, in _create_user
    user.save(using=self._db)
  File "C:\Users\PC\AppData\Local\Programs\Python\Python310\lib\site-packages\django\contrib\auth\base_user.py", line 67, in save
    super().save(*args, **kwargs)
  File "C:\Users\PC\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\base.py", line 726, in save
    self.save_base(using=using, force_insert=force_insert,
  File "C:\Users\PC\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\base.py", line 763, in save_base
    updated = self._save_table(
  File "C:\Users\PC\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\base.py", line 868, in _save_table
    results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
  File "C:\Users\PC\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\base.py", line 906, in _do_insert
    return manager._insert(
  File "C:\Users\PC\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\PC\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\query.py", line 1270, in _insert
    return query.get_compiler(using=using).execute_sql(returning_fields)
  File "C:\Users\PC\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\sql\compiler.py", line 1416, in execute_sql
    cursor.execute(sql, params)
  File "C:\Users\PC\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\utils.py", line 98, in execute
    return super().execute(sql, params)
  File "C:\Users\PC\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\utils.py", line 66, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "C:\Users\PC\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "C:\Users\PC\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\utils.py", line 79, in _execute
    with self.db.wrap_database_errors:
  File "C:\Users\PC\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\utils.py", line 90, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "C:\Users\PC\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\PC\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: UNIQUE constraint failed: accounts_user.email
4

2 回答 2

1

UNIQUE constraint failed是一个 SQL 错误,这意味着该列中已经存在相同的值,这意味着您在数据库中已经有一个用户使用该电子邮件。

于 2022-01-31T01:30:49.863 回答
0

根据文件

REQUIRED_FIELDS

通过 createsuperuser 管理命令创建用户时将提示输入的字段名称列表。系统将提示用户为这些字段中的每一个提供一个值。它必须包含空白为 False 或未定义的任何字段,并且可能包含您希望在交互式创建用户时提示输入的其他字段。REQUIRED_FIELDS 对 Django 的其他部分没有影响,比如在 admin 中创建用户

所以你REQUIRED_FIELDS应该是['email']

笔记

REQUIRED_FIELDS 必须包含用户模型上的所有必填字段,但不应包含 USERNAME_FIELD 或密码,因为这些字段将始终被提示输入

于 2022-01-30T23:30:39.623 回答