Django自定义User模型执行createsuperuser时触发非空约束错误
自定义Django User模型执行createsuperuser时触发非空约束错误
自定义继承AbstractUser的User模型后,执行python manage.py createsuperuser命令,绕过密码验证后触发错误:
django.db.utils.IntegrityError: NOT NULL constraint failed: hospital_user.date_of_birth
模型代码
from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class User(AbstractUser): GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ('O', 'Other'), ) USER_TYPE = ( ('S', 'Super Admin'), ('A', 'Admin'), ('P', 'Patient'), ('D', 'Doctor'), ('U', 'User'), ) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) date_of_birth = models.DateField(null=True, default=None) gender = models.CharField(max_length=1, choices=GENDER_CHOICES) user_type = models.CharField(max_length=1, choices=USER_TYPE) username = models.EmailField(unique=True) email = models.EmailField(unique=True) phone = models.CharField(max_length=15, blank=True, null=True) address = models.TextField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) REQUIRED_FIELDS = ['email', 'password'] def __str__(self): return f"{self.first_name} {self.last_name}"
执行命令
python manage.py createsuperuser
错误信息
Username: admin@admin.com Password: Password (again): The password is too similar to the username. This password is too common. Bypass password validation and create user anyway? [y/N]: y Traceback (most recent call last): File "/home/foysal/.local/lib/python3.10/site-packages/django/db/backends/utils.py", line 105, in _execute return self.cursor.execute(sql, params) File "/home/foysal/.local/lib/python3.10/site-packages/django/db/backends/sqlite3/base.py", line 329, in execute return super().execute(query, params) sqlite3.IntegrityError: NOT NULL constraint failed: hospital_user.date_of_birth The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/foysal/Documents/pYtHoN/hospital_management/manage.py", line 22, in <module> main() File "/home/foysal/Documents/pYtHoN/hospital_management/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/foysal/.local/lib/python3.10/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/home/foysal/.local/lib/python3.10/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/foysal/.local/lib/python3.10/site-packages/django/core/management/base.py", line 413, in run_from_argv self.execute(*args, **cmd_options) File "/home/foysal/.local/lib/python3.10/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 89, in execute return super().execute(*args, **options) File "/home/foysal/.local/lib/python3.10/site-packages/django/core/management/base.py", line 459, in execute output = self.handle(*args, **options) File "/home/foysal/.local/lib/python3.10/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 238, in handle self.UserModel._default_manager.db_manager(database).create_superuser( File "/home/foysal/.local/lib/python3.10/site-packages/django/contrib/auth/models.py", line 172, in create_superuser return self._create_user(username, email, password, **extra_fields) File "/home/foysal/.local/lib/python3.10/site-packages/django/contrib/auth/models.py", line 155, in _create_user user.save(using=self._db) File "/home/foysal/.local/lib/python3.10/site-packages/django/contrib/auth/base_user.py", line 78, in save super().save(*args, **kwargs) File "/home/foysal/.local/lib/python3.10/site-packages/django/db/models/base.py", line 822, in save self.save_base( File "/home/foysal/.local/lib/python3.10/site-packages/django/db/models/base.py", line 909, in save_base updated = self._save_table( File "/home/foysal/.local/lib/python3.10/site-packages/django/db/models/base.py", line 1067, in _save_table results = self._do_insert( File "/home/foysal/.local/lib/python3.10/site-packages/django/db/models/base.py", line 1108, in _do_insert return manager._insert( File "/home/foysal/.local/lib/python3.10/site-packages/django/db/models/manager.py", line 87, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/foysal/.local/lib/python3.10/site-packages/django/db/models/query.py", line 1847, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "/home/foysal/.local/lib/python3.10/site-packages/django/db/models/sql/compiler.py", line 1823, in execute_sql cursor.execute(sql, params) File "/home/foysal/.local/lib/python3.10/site-packages/django/db/backends/utils.py", line 122, in execute return super().execute(sql, params) File "/home/foysal/.local/lib/python3.10/site-packages/django/db/backends/utils.py", line 79, in execute return self._execute_with_wrappers( File "/home/foysal/.local/lib/python3.10/site-packages/django/db/backends/utils.py", line 92, in _execute_with_wrappers return executor(sql, params, many, context) File "/home/foysal/.local/lib/python3.10/site-packages/django/db/backends/utils.py", line 100, in _execute with self.db.wrap_database_errors: File "/home/foysal/.local/lib/python3.10/site-packages/django/db/utils.py", line 91, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/home/foysal/.local/lib/python3.10/site-packages/django/db/backends/utils.py", line 105, in _execute return self.cursor.execute(sql, params) File "/home/foysal/.local/lib/python3.10/site-packages/django/db/backends/sqlite3/base.py", line 329, in execute return super().execute(query, params) django.db.utils.IntegrityError: NOT NULL constraint failed: hospital_user.date_of_birth
解决方法
1. 修正REQUIRED_FIELDS配置
createsuperuser命令只会提示输入REQUIRED_FIELDS中的字段,你的模型里first_name、last_name、gender、user_type都是必填字段,却没加入REQUIRED_FIELDS,导致创建时没有提供这些值,触发数据库非空约束。修改如下:
REQUIRED_FIELDS = ['email', 'first_name', 'last_name', 'gender', 'user_type']
注意:password不需要加入,命令会单独提示输入密码。
2. 确保数据库迁移生效
如果之前的迁移文件没有正确应用date_of_birth的null=True设置,重新生成并执行迁移:
python manage.py makemigrations python manage.py migrate
3. 自定义超级用户创建逻辑(可选)
如果希望创建超级用户时自动填充默认值(比如默认用户类型为超级管理员),可以重写模型的create_superuser方法:
class User(AbstractUser): # ... 其他原有代码 ... @classmethod def create_superuser(cls, username, email, password=None, **extra_fields): # 强制设置超级管理员类型 extra_fields.setdefault('user_type', 'S') # 可添加其他字段默认值,比如gender、date_of_birth等 extra_fields.setdefault('gender', 'M') extra_fields.setdefault('date_of_birth', None) return super().create_superuser(username, email, password, **extra_fields)
内容的提问来源于stack exchange,提问作者abu abu
相关产品推荐
相关产品推荐

