【问题标题】:Configure django UserManager to input date of birth for superuser?配置 django UserManager 为超级用户输入出生日期?
【发布时间】:2013-02-24 04:00:09
【问题描述】:

通过创建我的自定义用户模型来搞乱 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']
...

【问题讨论】:

    标签: python django django-users


    【解决方案1】:

    您需要覆盖从AbstractUser 继承的模型中的REQUIRED_FIELDS。浏览contrib/auth/models.py 可以注意到AbstractBaseUser 有REQUIRED_FIELDS = [] 和AbstractUser 有REQUIRED_FIELDS = ['email']。我的猜测是你应该有类似的东西:

    class MyCoolUserModel(AbstractUser):
        REQUIRED_FIELDS = ['email', 'dob']
        ...
    

    编辑:不再是猜测。它有效。

    一般来说,您可以通过查看 contrib/auth/management/commands/createsuperuser.py 来了解 createsuperuser 的功能。任何非身份验证命令都可以位于core/management/commands/。几乎任何manage.py 问题都可以通过查看命令源来解决。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 2019-01-26
      • 2022-06-16
      • 1970-01-01
      • 2022-01-18
      • 2021-11-20
      • 1970-01-01
      相关资源
      最近更新 更多