Django custom user model, cant login to django admin panel

Viewed 248

I have a custom user model which uses phone number as username. but for some reason, I can't log in to the admin panel.

Note: I can create a superuser through CLI successfully. but when I try to log in it says: Please enter the correct phone and password for a staff account. Note that both fields may be case-sensitive.

custom user model, otp_auth_user.models.User:

class User(AbstractBaseUser, PermissionsMixin):
    """ Custom user model """
    phone = PhoneNumberField(unique=True)
    full_name = models.CharField(max_length=255)
    verification_code = models.CharField(default="",
                                         max_length=5)

    is_staff = models.BooleanField(default=False)

    objects = UserManager()


    USERNAME_FIELD = "phone"

    def __str__(self):
        return self.full_name

custom user manager, otp_auth_user.models.UserManager:

class UserManager(BaseUserManager):

    def create_user(self, phone, full_name, password=None, **extra_fields):

        validate_international_phonenumber(phone)
        
        if not phone:
            raise ValueError("a phone number must be provided.")

        user = self.model(
            phone=phone,
            full_name=full_name,
            verification_code = generate_verification_code(),
            **extra_fields
        )

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

        return user

    def create_superuser(self, phone, password):
        validate_international_phonenumber(phone)

        user = self.create_user(phone,
                                password)

  
        user.is_staff = True
        user.is_superuser = True
        user.save(using=self._db)

        return user

user serializer class, otp_auth_user.serializers.UserSerializer:

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = get_user_model()
        fields = ["id", "phone", "full_name"]
        extra_kwargs = {
            "id": {"read_only": True}
        }

Settings.py:

AUTH_USER_MODEL = "otp_auth_user.User"

EDIT: When I try to check the superuser password via Django shell and I used the password that I used when creating a new superuser it returned False that's weird..., password is hashed and user.check_password('admin') is returning False

1 Answers

Second argument of create_user method is full_name. So you are passing password as a full name in create_superuser:

def create_superuser(self, phone, password):
    validate_international_phonenumber(phone)

    user = self.create_user(phone,
                            password)

You should explicitly pass password:

def create_superuser(self, phone, password):
    validate_international_phonenumber(phone)

    user = self.create_user(phone=phone,
                            full_name=phone 
                            password=password)

After this you need to recreate superuser from CLI.

Related