Skip to main content
 首页 » 编程设计

python之如何更改自定义用户模型的经理

2025年02月15日36myhome

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

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' 

用户模型有效,但存在一个问题。我无法创建 super 用户:
(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使用的方法将用户名作为必需参数。我读过 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模型。似乎没有文档告诉我在哪里实际设置 CustomUserManagerUser实际管理人模型。有人能告诉我怎么做吗?

请您参考如下方法:

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

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

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

至于:

There seems to be no documentation telling me where to actually set the CustomUserManager as the actual manager for the User model.



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