django 属性错误:“UserManager”对象没有属性“create_superuser”

2izufjch  于 2023-05-08  发布在  Go
关注(0)|答案(3)|浏览(144)

我已经按照Django设置了customUser管理器,但我仍然收到属性错误。我不知道还有什么是错的。

class UserManager(BaseUserManager):
    def create_user(self, email, date_of_birth, password=None):
        """
        Creates and saves a User with the given email, date of
        birth and password.
        """
        if not email:
            raise ValueError('Users must have an email address')

        user = self.model(
            email=self.normalize_email(email),
        )

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, date_of_birth, password):
        """
        Creates and saves a superuser with the given email, date of
        birth and password.
        """
        user = self.create_user(email,
            password=password,
            date_of_birth=date_of_birth
        )
        user.is_admin = True
        user.save(using=self._db)
        return user

class User(AbstractBaseUser):
    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique=True,
    )
    date_of_birth = models.DateField()
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)

    objects = UserManager()

    USERNAME_FIELD = 'email'

    def get_full_name(self):
        # The user is identified by their email address
        return self.email

    def get_short_name(self):
        # The user is identified by their email address
        return self.email

    def __str__(self):              # __unicode__ on Python 2
        return self.email

我已经定义了用户和超级用户。并将该对象设置为UserManager。
Traceback是:

Traceback (most recent call last):
  File "manage.py", line 10, in <module> execute_from_command_line(sys.argv)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
utility.execute()
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/base.py", line 393, in run_from_argv
self.execute(*args, **cmd_options)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 50, in execute
    return super(Command, self).execute(*args, **options)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/base.py", line 444, in execute
    output = self.handle(*args, **options)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 149, in handle
           self.UserModel._default_manager.db_manager(database).create_superuser(**user_data)
 AttributeError: 'UserManager' object has no attribute 'create_superuser'

我运行的代码是:

python manage.py createsuperuser
cngwdvgl

cngwdvgl1#

我猜你有Django 1.8下面是创建继承AbstractUser模型的自己的模型所必须做的事情。
在您的模型中:

from django.contrib.auth.models import AbstractUser
from django.db import models

class User(AbstractUser):
  pass

您的User模型将自动继承AbstractUserUserManager,然后您不必编写:objects = YourUserManager(),除非你想扩展它。在这种情况下,您可以执行以下操作:

from django.contrib.auth.models import AbstractUser, UserManager as AbstractUserManager
from django.db import models

class UserManager(AbstractUserManager):
  pass

class User(AbstractUser):
    objects = UserManager()

在你的Django应用中使用settings.py定义User模型:

# <module_name>.<user_model_name>
AUTH_USER_MODEL = 'user.User'

现在,当您想要在其他应用中导入用户模型以使用它时,请使用settings.AUTH_USER_MODEL。下面是一个例子:

from django.db import models
from django.conf import settings

class Token(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL)

阅读正确的Django文档以获取更多信息:扩展现有用户模型

wi3ka0sx

wi3ka0sx2#

尝试以下操作并根据您的要求替换字段:

class UserManager(BaseUserManager):

    def create_user(self, email, password=None,is_active=True,is_staff=False,is_admin=False):
        """
        Creates and saves a User with the given email and password.
        """
        if not email:
            raise ValueError('Users must have an email address')

        user = self.model(
            email=self.normalize_email(email),
        )

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_staffuser(self, email, password):
        """
        Creates and saves a staff user with the given email and password.
        """
        user = self.create_user(
            email,
            password=password,
        )
        user.staff = True
        user.save(using=self._db)
        return user

    def create_superuser(self, email, password):
        """
        Creates and saves a superuser with the given email and password.
        """
        user = self.create_user(
            email,
            password=password,
        )
        user.staff = True
        user.admin = True
        user.save(using=self._db)
        return user
13z8s7eq

13z8s7eq3#

有同样的错误,并被定向在这里时,搜索答案,我的问题最终是我的def创建超级用户和创建用户不在同一列

def create_superuser(self, email, user_name, first_name, password, **other_fields):

    other_fields.setdefault('is_staff',True)
    other_fields.setdefault('is_superuser',True)
    other_fields.setdefault('is_active',True)

    if other_fields.get('is_staff') is not True:
     raise ValueError(
       'Superuser must be assigned to is_staff=True.')
    if other_fields.get('is_superuser') is not True:
     raise ValueError(
       'Superuser must be assigned to is_superuser=True.')

    return self.create_user(email, user_name, first_name, password, **other_fields)

  def create_user(self, email, user_name, first_name, password, **other_fields):
  
      if not email:  
        raise ValueError(_('You must provide an email address'))

      email = self.normalize_email(email)
      user = self.model(email=email, user_name=user_name,
                        first_name=first_name, **other_fields)
      user.set_password(password)
      user.save()
      return user

当比较我的代码和你的代码时,区别在于我的超级用户排在第一位,返回值引用了'create_user'。这是我的NewUser类代码:

class NewUser (AbstractBaseUser, PermissionsMixin):

  email = models.EmailField(_('email address'), unique=True)
  user_name = models.CharField(max_length=150, unique=True)
  first_name = models.CharField(max_length=150)
  start_date = models.DateTimeField(default=timezone.now)
  about = models.TextField(_('about'), max_length=500, blank=True)
  is_staff = models.BooleanField(default=False)
  is_active = models.BooleanField(default=False)

  objects = CustomAccountManager()

  USERNAME_FIELD = 'email'
  REQUIRED_FIELDS = ['user_name', 'first_name']

  def __str__(self):
    return self.user_name

我的进口from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager

相关问题