(2019-02-07) Michael Herman => highly recommended to set up a custom User when starting a new Django project ¶
See also
Contents
Advice ¶
It’s highly recommended to set up a custom User model when starting a new Django project. Without it, you will need to create another model (like UserProfile) and link it to the Django User model with a OneToOneField if you want to add new fields to the User model.
managers.py ¶
1 from django.contrib.auth.base_user import BaseUserManager
2 from django.utils.translation import ugettext_lazy as _
3
4
5 class CustomUserManager(BaseUserManager):
6 """
7 Custom user model manager where email is the unique identifiers
8 for authentication instead of usernames.
9 """
10 def create_user(self, email, password, **extra_fields):
11 """
12 Create and save a User with the given email and password.
13 """
14 if not email:
15 raise ValueError(_('The Email must be set'))
16 email = self.normalize_email(email)
17 user = self.model(email=email, **extra_fields)
18 user.set_password(password)
19 user.save()
20 return user
21
22 def create_superuser(self, email, password, **extra_fields):
23 """
24 Create and save a SuperUser with the given email and password.
25 """
26 extra_fields.setdefault('is_staff', True)
27 extra_fields.setdefault('is_superuser', True)
28 extra_fields.setdefault('is_active', True)
29
30 if extra_fields.get('is_staff') is not True:
31 raise ValueError(_('Superuser must have is_staff=True.'))
32 if extra_fields.get('is_superuser') is not True:
33 raise ValueError(_('Superuser must have is_superuser=True.'))
34 return self.create_user(email, password, **extra_fields)
models.py ¶
1 from django.db import models
2 from django.contrib.auth.models import AbstractUser
3 from django.utils.translation import ugettext_lazy as _
4
5 from .managers import CustomUserManager
6
7
8 class CustomUser(AbstractUser):
9 username = None
10 email = models.EmailField(_('email address'), unique=True)
11
12 USERNAME_FIELD = 'email'
13 REQUIRED_FIELDS = []
14
15 objects = CustomUserManager()
16
17 def __str__(self):
18 return self.email