Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save farhad0085/33d0366807bdfaa5e558e97a84e7642e to your computer and use it in GitHub Desktop.

Select an option

Save farhad0085/33d0366807bdfaa5e558e97a84e7642e to your computer and use it in GitHub Desktop.
Custom User Model along with custom manager

Create Custom User Model along with custom manager

Steps

  1. First create a new model
  2. Make a new manager for objects
  3. Change default auth model in settings
from django.contrib.auth.models import BaseUserManager
class UserProfileManager(BaseUserManager):
"""Helps django work with our custom user model"""
def create_user(self, email, name, password=None):
"""Creates a new user profile object"""
if not email:
raise ValueError("User must have an email address")
email = self.normalize_email(email)
user = self.model(email=email, name=name)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, name, password):
""" Creates and saves a new superuser with given details"""
user = self.create_user(email, name, password)
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
from .managers import UserProfileManager
class UserProfile(AbstractBaseUser, PermissionsMixin):
""" Represents a user profile inside our system """
email = models.EmailField(max_length=255, unique=True)
name = models.CharField(max_length=255)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
objects = UserProfileManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['name']
def get_full_name(self):
""" Used to get a users full name"""
return self.name
def get_short_name(self):
""" Used to get a users short name"""
return self.name
def __str__(self):
"Django uses this when it need to convert the object to a string"
return self.email
AUTH_USER_MODEL = 'app_name.UserProfile' # don't need to specify models.py, just app name and model name
ACCOUNT_USER_MODEL_USERNAME_FIELD = None
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_AUTHENTICATION_METHOD = 'email'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment