Skip to content

Instantly share code, notes, and snippets.

@raykipkorir
Last active June 7, 2023 05:04
Show Gist options
  • Save raykipkorir/c04618c8ed1f47137c8786080dbceb8d to your computer and use it in GitHub Desktop.
Save raykipkorir/c04618c8ed1f47137c8786080dbceb8d to your computer and use it in GitHub Desktop.
Custom user manager in Django to get rid of username field.
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
from django.contrib.auth.models import PermissionsMixin
from django.db import models
from django.utils import timezone
class UserManager(BaseUserManager):
"""Custom user manager"""
use_in_migrations = True
def _create_user(self, email, password, **extra_fields):
if not email:
raise ValueError("Users must have an email address")
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email=None, password=None, **extra_fields):
"""Create normal user"""
extra_fields.setdefault("is_staff", False)
extra_fields.setdefault("is_superuser", False)
return self._create_user(email, password, **extra_fields)
def create_superuser(self, email=None, password=None, **extra_fields):
"""Create superuser"""
extra_fields.setdefault("is_staff", True)
extra_fields.setdefault("is_superuser", True)
if extra_fields.get("is_staff") is not True:
raise ValueError("Superuser must have is_staff=True.")
if extra_fields.get("is_superuser") is not True:
raise ValueError("Superuser must have is_superuser=True.")
return self._create_user(email, password, **extra_fields)
class User(PermissionsMixin, AbstractBaseUser):
"""Custom user model"""
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.EmailField(unique=True)
is_staff = models.BooleanField(
"staff status",
default=False,
help_text="Designates whether the user can log into this admin site.",
)
is_active = models.BooleanField(
"active",
default=True,
help_text=
"Designates whether this user should be treated as active. "
"Unselect this instead of deleting accounts."
,
)
date_joined = models.DateTimeField("date joined", default=timezone.now)
objects = UserManager()
USERNAME_FIELD = "email"
REQUIRED_FIELDS = ["first_name", "last_name"]
@property
def fullname(self) -> str:
"""Concatenate first_name and last_name"""
return f"{self.first_name} {self.last_name}"
def __str__(self) -> str:
return f"{self.fullname}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment