Create a custom User model in Django 4.0
These steps were following this from?Django documentation to use custom user.
Before starting
It is highly recommended doing this reinterpretation of Use model at the very beginning of the project. Take in mind this requires a reinterpretation of the User model, so if you already have run migrations, you will need to make an empty apply of the migration; this means that you will lose the database data, so it’s recommendable to make a backup before do that if there are valuable data on databases.
Step-by-step
This example will?be for a User model with email (as identifier) and name as parameters.
python manage.py startapp users
2. Add users to installed apps section in project settings (Project/settings.py) file, and in the same file add:
AUTH_USER_MODEL = ‘users.User’
3. The file?models.py?must look like this:
领英推荐
from django.contrib.auth.models import PermissionsMixi
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 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
4. Now you will now have to apply the migrations running:
python manage.py migrate
If you have had applied migrations before, you may get an error like this:
django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency users.0001_initial on database ‘default’.
To fix that, you may apply the migration with?django.contrib.admin?removed from ‘installed apps’?property?on settings Django file, and also removing admin’s URL on?urls.py?Django file. After the migration, you can recover admin’s lines and continue developing as well.
5. And a custom user model is done!
Conclusions
Basically what you have to do, is to tell Django which model will be the AUTH model (step 2), and then create the model (step 3), it would be easier if you extend the original User model (AbstractBaseUser), and create a Manager for the model (to be able to use commands like?createsuperuser?in the terminal).