Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
3
Help us understand the problem. What is going on with this article?
@Yuji_6523

【メモ】Django カスタムユーザーモデル

More than 1 year has passed since last update.

環境
Python = 3.7.5
Django = 3.0.3

Djangoでは、カスタムユーザーモデルの使用を推奨されているので、メモとして今回作成したカスタムユーザーモデルのコードを記載します。

最近では、ユーザーIDではなくてEmailアドレスを使用してログインを行うのが主流ですので、Emailアドレスとパスワードを使用して、ログインするようにしました。

参考になれば嬉しいです.

conf(your_project_name)/settings.py
#(省略)

# 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'

#(省略)

accounts/models.py
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
3
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
3
Help us understand the problem. What is going on with this article?