【笔记】Django 自定义用户模型

环境
Python = 3.7.5
Django = 3.0.3

环境
Python版本为3.7.5
Django版本为3.0.3

由于Django推荐使用自定义用户模型,因此我将在此记下本次创建的自定义用户模型的代码作为备忘录。

最近,主流趋势是使用电子邮件地址而不是用户ID进行登录,因此我们采用了使用电子邮件地址和密码进行登录的方式。

如果有帮助的话,我会很高兴。


#(省略)

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # 追加アプリケーション #
    'post.apps.PostConfig',
    'accounts.apps.AccountsConfig',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'conf.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, ('templates'))],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

# カスタムユーザーモデルを使用する宣言。  #
AUTH_USER_MODEL = 'accounts.CustomUser'  #←これを追加

WSGI_APPLICATION = 'conf.wsgi.application'

#(省略)

from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager


class CustomUserManager(BaseUserManager):
    def create_user(self, email, username, password, **extra_fields):
        # Creates and saves a User with the given email, date of birth and password.

        if not email:
            raise ValueError('Users must have an email address.')
        if not username:
            raise ValueError('Users must have a username.')

        email = self.normalize_email(email)
        user = self.model(
            email = email,
            username = username,
        )

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, username, password, **extra_fields):
        user = self.create_user(
            email,
            password = password,
            username = username,
        )

        user.is_admin = True
        user.is_staff = True
        user.is_superuser = True
        user.save(using=self._db)
        return user


class CustomUser(AbstractBaseUser):
    email         = models.EmailField('email', max_length=50, unique=True)
    username      = models.CharField('username', max_length=50, unique=True)
    first_name    = models.CharField('first name', max_length=50, blank=True)
    last_name     = models.CharField('last name', max_length=50, blank=True)
    date_of_birth = models.DateField(null=True, blank=True)
    date_joined   = models.DateTimeField('date joined', auto_now_add=True)
    last_login    = models.DateTimeField('last login', auto_now_add=True)
    is_admin      = models.BooleanField(default=False)
    is_active     = models.BooleanField(default=True)
    is_staff      = models.BooleanField(default=False)
    is_superuser  = models.BooleanField(default=False)

    # use email to login #
    USERNAME_FIELD = 'email'
    # required username for  #
    REQUIRED_FIELDS = ['username']

    # to use CustomUserManager #
    objects = CustomUserManager()

    def __str__(self):
        return self.email

    # to have a specific permission? #
    def has_perm(self, perm, obj=None):
        return self.is_admin

    # to have permissions to view the app `app_label #
    def has_module_perms(self, app_label):
        return True
广告
将在 10 秒后关闭
bannerAds