Reputation: 1865
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
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:
.create_user(…)
[Django-doc] to create a user;.create_superuser(…)
[Django-doc] to create a user that is a superuser; andwith_perm(…)
[Django-doc] that returns a set of User
objects that have a given permission.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