I have my own custom User model, and its own Manger too.
models:
class MyUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(max_length=255, unique=True)
first_name = models.CharField(max_length=35)
last_name = models.CharField(max_length=35)
username = models.CharField(max_length=70, unique=True)
date_of_birth = models.DateField()
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
@property
def is_staff(self):
return self.is_admin
def get_full_name(self):
return ('%s %s') % (self.first_name, self.last_name)
def get_short_name(self):
return self.username
objects = MyUserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name', 'username', 'date_of_birth']
manager:
class MyUserManager(BaseUserManager):
def create_user(self, email, first_name, last_name, username, date_of_birth, password=None, **kwargs):
if not email:
raise ValueError('User must have an email address')
user = self.model(
email=self.normalize_email(email),
first_name=first_name,
last_name=last_name,
username=username,
date_of_birth=date_of_birth,
**kwargs
)
user.set_password(self.cleaned_data["password"])
user.save(using=self._db)
return user
def create_superuser(self, email, first_name, last_name, username, date_of_birth, password, **kwargs):
user = self.create_user(
email,
first_name=first_name,
last_name=last_name,
username=username,
date_of_birth=date_of_birth,
password=password,
is_superuser=True,
**kwargs
)
user.is_admin = True
user.save(using=self._db)
return user
Everything works when creating a new user without any errors. But when I try to login I can't. So I checked the user's password to confirm and the password is displayed as plain text strongpassword
, and when changed admin form to get the hashed password using ReadOnlyPasswordHashField
I get an error inside the password field, even though I used set_password()
for the Manger inside the create_user()
function.
Invalid password format or unknown hashing algorithm
However, if I manually do set_password('strongpassword')
for that user it is then hashed. Could you please help me solve this problem. Thank you.
self.create_superuser
is not calling your customself.create_user
, rather calling the default. Can you put a breakpoint and inspect ? – Hovercraftfrom django.contrib.auth.hashers import make_password
. So just usemake_password(password)
. – Gabby