Search⌘ K
AI Features

Creating the User and Superuser

Explore how to create custom user and superuser models in Django by writing UserManager methods, setting up migrations, and testing the models within the Django shell. Understand the process of integrating these user models into the authentication system, which includes handling database changes and preparing data for client access.

We'll cover the following...

Let’s write UserManager so we can have methods to create a user and a superuser:

Python 3.8
class UserManager(BaseUserManager):
def get_object_by_public_id(self, public_id):
try:
instance = self.get(public_id=public_id)
return instance
except (ObjectDoesNotExist, ValueError, TypeError):
return Http404
def 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 user
def 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 = True
user.is_staff = True
user.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 using the save() method.

The create_superuser method also behaves in accordance with the create_user method—this makes sense because, ...