问题:
使用manage.py时,我无法创建超级用户,并且它会以错误AttributeError: 'UserManager' object has no attribute 'create_superuser’
进行响应。然后,我尝试手动导入所有必需的模型,并在python shell中运行它,但遇到了相同的障碍。
目标: 使用基本管理的继承类正确创建超级用户
代码:
from django.contrib.auth.models import AbstractUser, BaseUserManager, Group
class UserManager(BaseUserManager):
def get_by_natural_key(self, username):
return self.get(username__iexact=username)
class User(AbstractUser):
objects = UserManager()
…
…
def __str__(self):
return ’{}’.format(self.id)
def save(self, *args, **kwargs):
self.full_clean()
super(FollowUser, self).save(*args, **kwargs)
答案 0 :(得分:1)
BaseUserManager没有任何称为create_superuser
的方法。您需要像这样将其添加到Manager类(从github粘贴的副本):
class UserManager(BaseUserManager):
def _create_user(self, username, email, password, **extra_fields):
"""
Create and save a user with the given username, email, and password.
"""
if not username:
raise ValueError('The given username must be set')
email = self.normalize_email(email)
username = self.model.normalize_username(username)
user = self.model(username=username, email=email, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, username, email, password, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
if extra_fields.get('is_staff') is not True:
raise ValueError('Superuser must have is_staff=True.')
if extra_fields.get('is_superuser') is not True:
raise ValueError('Superuser must have is_superuser=True.')
return self._create_user(username, email, password, **extra_fields)
或者,您可以从UserManager类中继承您的Manager。