Creating the User and Superuser
Learn to implement the UserManager class for the User model to create a user and a superuser.
We'll cover the following...
Let’s write UserManager
so we can have methods to create a user and a superuser:
Press + to interact
class UserManager(BaseUserManager):def get_object_by_public_id(self, public_id):try:instance = self.get(public_id=public_id)return instanceexcept (ObjectDoesNotExist, ValueError, TypeError):return Http404def create_user(self, username, email, password=None, **kwargs):"""Create and return a `User` with an email, phone number, username and password."""if username is None:raise TypeError('Users must have a username.')if email is None:raise TypeError('Users must have an email.')if password is None:raise TypeError('User must have an email.')user = self.model(username=username, email=self.normalize_email(email), **kwargs)user.set_password(password)user.save(using=self._db)return userdef create_superuser(self, username, email, password, **kwargs):"""Create and return a `User` with superuser (admin) permissions."""if password is None:raise TypeError('Superusers must have a password.')if email is None:raise TypeError('Superusers must have an email.')if username is None:raise TypeError('Superusers must have an username.')user = self.create_user(username, email, password, **kwargs)user.is_superuser = Trueuser.is_staff = Trueuser.save(using=self._db)return user
For the create_user
method, we are basically making sure that fields such as password
, email
, username
, first_name
, and last_name
are not None
. If everything is good, we can confidently call the model, set a password, and save the user in the table.
This is done ...