如何更改自定义用户模型

时间:2018-01-15 11:32:03

标签: python django

我已经定义了一个自定义用户模型:

class User(AbstractUser):

    REQUIRED_FIELDS = []
    USERNAME_FIELD = 'email'
    email = models.EmailField(
        _('email address'),
        max_length=150,
        unique=True,
        help_text=_('Required. 150 characters or fewer. Must be a valid email address.'),
        error_messages={
            'unique':_("A user with that email address already exists."),
        },
    )

要使用电子邮件地址而不是用户名。

我把它放在设置中:

# custom user model
AUTH_USER_MODEL = 'workoutcal.User'

用户模型有效,但有一个问题。我无法创建超级用户:

(workout) n155-p250:workout sahandzarrinkoub$ ./manage.py createsuperuser
Email address: sahandz@kth.se
Password: 
Password (again): 
Traceback (most recent call last):
  File "./manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
    utility.execute()
  File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 59, in execute
    return super().execute(*args, **options)
  File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute
    output = self.handle(*args, **options)
  File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 179, in handle
    self.UserModel._default_manager.db_manager(database).create_superuser(**user_data)
TypeError: create_superuser() missing 1 required positional argument: 'username'

似乎使用的create_superuser方法将username作为必需参数。我已经在docs中读到了我需要实现自己的CustomUserManager。我已经在这里这样做了:

class CustomUserManager(BaseUserManager):
    def _create_user(self, email, password, is_staff, is_superuser, **extra_fields):
        now = timezone.now()
        if not email:
            raise ValueError('email must be set')
        email = self.normalize_email(email)
        user = User(email = email, is_staff=is_staff,
                    is_superuser=is_superuser, date_joined=now,
                    **extra_fields)
        user.set_password(password)
        user.save()
        return user

    def create_user(self, email, password, **extra_fields):
        return self._create_user(email, password, False, False, **extra_fields)

    def create_superuser(self, email, password, **extra_fields):
        return self._create_user(email, password, True, True, **extra_fields)

很明显,我的CustomUserManager 未管理 User 模型。似乎没有文档告诉我实际将CustomUserManager设置为User模型的实际管理员的位置。有人能告诉我怎么做吗?

1 个答案:

答案 0 :(得分:5)

您还需要告诉新用户使用新经理:

class User(AbstractUser): # in your custom user
    #...
    objects = CustomUserManager()
    #...

Django做同样的事情in the source code at line 325

至于:

  

似乎没有文档告诉我在哪里将CustomUserManager实际设置为User模型的实际管理器。

是的,实际上还有一个很好的文档,但是以更一般的方式解释: https://docs.djangoproject.com/en/2.0/topics/db/managers/