使用 AbstractBaseUser 在 Django 中创建自定义用户模型
creating a custom user model in django using AbstractBaseUser
我正在尝试创建自定义用户模型,当我 运行 python manage.py 创建超级用户时,它会提示我输入用户名、密码和确认密码,当我点击输入之后我得到这个错误
django.db.utils.IntegrityError: UNIQUE constraint failed: accounts_user.email
model.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
根据 documentions:
REQUIRED_FIELDS
A list of the field names that will be prompted for when creating a
user via the createsuperuser management command. The user will be
prompted to supply a value for each of these fields. It must include
any field for which blank is False or undefined and may include
additional fields you want prompted for when a user is created
interactively. REQUIRED_FIELDS has no effect in other parts of Django,
like creating a user in the admin
所以你的 REQUIRED_FIELDS
应该是 ['email']
Note
REQUIRED_FIELDS must contain all required fields on your user model,
but should not contain the USERNAME_FIELD or password as these fields
will always be prompted for
UNIQUE constraint failed
是一个 SQL 错误,这意味着列中已存在相同的值,这意味着数据库中已经有一个使用该电子邮件的用户。
我正在尝试创建自定义用户模型,当我 运行 python manage.py 创建超级用户时,它会提示我输入用户名、密码和确认密码,当我点击输入之后我得到这个错误
django.db.utils.IntegrityError: UNIQUE constraint failed: accounts_user.email
model.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
根据 documentions:
REQUIRED_FIELDS
A list of the field names that will be prompted for when creating a user via the createsuperuser management command. The user will be prompted to supply a value for each of these fields. It must include any field for which blank is False or undefined and may include additional fields you want prompted for when a user is created interactively. REQUIRED_FIELDS has no effect in other parts of Django, like creating a user in the admin
所以你的 REQUIRED_FIELDS
应该是 ['email']
Note
REQUIRED_FIELDS must contain all required fields on your user model, but should not contain the USERNAME_FIELD or password as these fields will always be prompted for
UNIQUE constraint failed
是一个 SQL 错误,这意味着列中已存在相同的值,这意味着数据库中已经有一个使用该电子邮件的用户。