django model manager user
To create a Django model manager for the User model, follow these steps:
- Import the necessary modules:
from django.contrib.auth.models import BaseUserManager
from django.utils import timezone
- Define a custom manager class that extends
BaseUserManager
:
class CustomUserManager(BaseUserManager):
- Implement the
create_user
method to create a regular user:
def create_user(self, email, password=None, extra_fields):
if not email:
raise ValueError('The Email field must be set')
email = self.normalize_email(email)
user = self.model(email=email, extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
- Implement the
create_superuser
method to create a superuser:
def create_superuser(self, email, password=None, extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
return self.create_user(email, password, extra_fields)
- Add the
objects
attribute to the User model and set it to an instance of your custom manager class:
class User(AbstractBaseUser, PermissionsMixin):
...
objects = CustomUserManager()
- Make any necessary migrations to update the database schema:
python manage.py makemigrations
python manage.py migrate
That's it! Now you have a custom model manager for the User model in Django.