通过创建我的自定义用户模型来搞乱 django 1.5。在我的模型中,我有一个必填字段 dob = DateTimeField()。我几乎将 UserManager 和 AbstractUser 保持不变。但是,当我尝试 python manage.py createsuperuser 时,我没有输入 dob,我得到了错误:
IntegrityError:“dob”列中的空值违反非空约束
如何编辑 UserManager 以允许我在终端中输入出生日期,并将输入配置为在数据库中存储为 DateTimeField?
编辑我的答案:
class UserManager(BaseUserManager):
def create_user(self, username, email=None, password=None, dob=None, **extra_fields):
"""
Creates and saves a User with the given username, email and password.
"""
now = timezone.now()
if not username:
raise ValueError('The given username must be set')
if not email:
raise ValueError('Email must be given')
email = UserManager.normalize_email(email)
user = self.model(username=username, email=email,
is_staff=False, is_active=True, is_superuser=False,
last_login=now, date_joined=now, dob=dob, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, username, email, password, dob, **extra_fields):
u = self.create_user(username, email, password, dob, **extra_fields)
u.is_staff = True
u.is_active = True
u.is_superuser = True
u.save(using=self._db)
return u
# ... in the user model:
...
REQUIRED_FIELDS = ['email', 'dob']
...