Abdullah Moudood
Abdullah Moudood

Reputation: 23

Django user.set_password(password) is not hashing the password

I have wrote Custom user Model in Django everything is working fine except password is not being hashed when but when I had created the superuser password was hashed here are my models for custom user and custom user manager model.py()

class CustomUser(AbstractUser):
    email = models.EmailField(_("email address"), null=False,blank=False,unique=True)
    USERNAME_FIELD='email'
    REQUIRED_FIELDS = ["username"]
    object=CustomUserManager()


class CustomUserManager(UserManager):
    def _create_user(self, username, email, password, **extra_fields):
        """
        Create and save a user with the given username, email, and password.
        """
        if not email:
            raise ValueError("The given email must be set")
        email = self.normalize_email(email)
        
        user = self.model(username=username, email=email, **extra_fields)
        user.set_password(password)  
        user.save(using=self._db)
        return user


    def create_user(self,username ,email, password, **extra_fields):
        extra_fields.setdefault("is_staff", False)
        extra_fields.setdefault("is_superuser", False)
        return self._create_user( username,email, password, **extra_fields)

    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)

admin.py

from django.contrib import admin from django.contrib.auth import get_user_model

admin.site.register(get_user_model())

should i use this from django.contrib.auth.hashers import make_password and how to use this

Upvotes: 0

Views: 117

Answers (1)

yedpodtrzitko
yedpodtrzitko

Reputation: 9359

you have to use UserAdmin (or class inherited from it), as changing the password is done via special password form instead of default text field

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
django.contrib.auth import get_user_model

admin.site.register(get_user_model(), UserAdmin)

Upvotes: 0

Related Questions