By default ,Django comes with a User
model that includes username,email, password and etc.However,to make changes using email instead of username you will need to customize this User
model.
2 Why Customize the User Model?.
Customizing the user model allows you to:
Use email as the login field instead of username.
Add the extra field like
phone_number
or `profile_picture.Implement Custom user roles and permissions.
3 Steps to Customize the User Model.
Step 1 :Create a Custom Model
Django recommends using Custom user model at the beginning of your project to avoid complications later.Here's how to define a custom user model:
1 Create the custom user model in app's models.py
file .
`
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.db import models
class UserManager(BaseUserManager):
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
def create_superuser(self, email, password=None, **extra_fields):
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(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(unique=True)
first_name = models.CharField(max_length=30, blank=True)
last_name = models.CharField(max_length=30, blank=True)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
date_joined = models.DateTimeField(auto_now_add=True)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name']
def __str__(self):
return self.email
`
In this example:
Top comments (0)