Jacq
Jacq

Reputation: 105

User Manager object has no attribute create_superuser

Problem: When using manage.py i’m unable to create a super user and it responds with the error AttributeError: 'UserManager' object has no attribute 'create_superuser’. I then tried to manually import all of the necessary models and run it in a python shell and was met with the same roadblock.

Goal: Properly create super user using inherited class of base manage

Code:

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)

Upvotes: 1

Views: 3479

Answers (1)

ruddra
ruddra

Reputation: 51938

BaseUserManager does not have any method called create_superuser. Either you need to add it to the Manager Class like this(copy pasted from 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)

Or, you can subclass your Manager from UserManager Class.

Upvotes: 7

Related Questions