Last active
February 13, 2022 23:07
-
-
Save alejandroacho/b58350dd23d6eb6552cd87cb38f6604c to your computer and use it in GitHub Desktop.
Custom use model in Django 4
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.contrib.auth.models import PermissionsMixin | |
from django.db import models | |
from django.utils.http import urlquote | |
from django.utils.translation import ugettext_lazy as _ | |
class CustomUserManager(BaseUserManager): | |
""" | |
Custom user model manager where email is the identifier for authentication | |
instead of usernames. | |
""" | |
def create_user(self, email, password, name, **extra_fields): | |
""" | |
Creates and saves a User with the given email and password. | |
""" | |
if not email: | |
raise ValueError('The given email must be set') | |
email = self.normalize_email(email) | |
user = self.model(email=email, | |
name=fname, | |
**extra_fields) | |
user.set_password(password) | |
user.save(using=self._db) | |
return user | |
def create_superuser(self, email, name, password, **extra_fields): | |
""" | |
Create and save a SuperUser with the given email and password. | |
Function needed to run <createsuperuser> django command. | |
""" | |
user = self.model(email=email, | |
name=name, | |
**extra_fields) | |
user.set_password(password) | |
user.is_admin = True | |
user.save(using=self._db) | |
return user | |
class User(AbstractBaseUser, PermissionsMixin): | |
username = None # ←- Here disables a field from AbstractBaseUser | |
email = models.EmailField('Email address', | |
unique = True, | |
error_messages = { | |
'unique': 'This email already exists.' | |
}) | |
name = models.CharField('First name', | |
blank = False, | |
max_length = 50) | |
is_admin = models.BooleanField('Admin status', | |
default = False) | |
USERNAME_FIELD = 'email' # ←- Here you told Django that this is the login param | |
REQUIRED_FIELDS = ['name'] | |
objects = CustomUserManager() # ←- Here you told Django that this is the manager | |
def __str__(self): | |
return self.email | |
def has_perm(self, perm, obj=None): | |
return self.is_admin | |
@property | |
def is_staff(self): | |
"Is the user a member of staff?" | |
# Simplest possible answer: All admins are staff | |
return self.is_admin |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment