Home > other >  Can't create superuser in Django using custom user
Can't create superuser in Django using custom user

Time:01-26

I got this error when i try to run manage.py createsuperuser

TypeError: UserManager.create_superuser() missing 1 required positional argument: 'username'

My User model:

class User(AbstractUser):
    name = models.CharField(max_length=32)
    email = models.CharField(max_length=140,  unique=True)
    password = models.CharField(max_length=140)
    username = None

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

and in my settings.py file:

AUTH_USER_MODEL = 'usuarios.User'

How can i solve this? Im new in Django, documentation is confused to me...

I already tried remove AUTH_USER_MODEL = 'usuarios.User' or remove username attribute from class User

CodePudding user response:

To create superuser with custom user model like above you have to implement the method create_superuser in the custom UserManager class some thing like bellow.and you need to specify username field in custom user model like bellow. Then specify the custom user model in the settings

class User(AbstractBaseUser,PermissionsMixin):

   name = models.CharField(max_length=255,null=True,blank=True)
   mobile = models.CharField("Mobile No",max_length=10,unique=True)
   is_active = models.BooleanField(default=True)
   
   objects = CustUserManager()     # custom object manager
   USERNAME_FIELD = 'mobile'   # custom username field (**in this case mobile**)

 class CustUserManager(BaseUserManager):

   def create_superuser(self,mobile,password=None,**extra_fields):
     user = self.create_user(mobile,password)
     user.is_superuser = True
     user.save(using=self._db)
   def create_user(self,email,account_no,password=None,**extra_fields):
      #code to create user like above
  • Related