timbram
timbram

Reputation: 1865

What is the purpose of the UserManager class in django?

What is the purpose of the UserManager class in django?

The documentation doesn't seem to really explain what it is for.

Upvotes: 2

Views: 905

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477180

The main purpose is to create (super)users. Since passwords are hashed, that is not simply achivable with a .create(…) [Django-doc].

The UserManager [Django-doc] is thus a Manager, with extra methods:

If we take a look at the standard UserManager implementation [GitHub], we see:

    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_user(self, username, email=None, password=None, **extra_fields):
        extra_fields.setdefault('is_staff', False)
        extra_fields.setdefault('is_superuser', False)
        return self._create_user(username, email, password, **extra_fields)

It will thus normalize both the username and email address, and furthermore use the .set_password(…) method [Django-doc] to set the password, to ensure that the password is hashed before saving it to the database.

Upvotes: 3

Related Questions