35
29

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Djangoでメールアドレスとパスワードでログインしてみる

Last updated at Posted at 2018-01-19

前置き

(Django2.01, Python3.6.4)

デフォルトだと usernamepassword なので、emailpassword でログインできるように変更してみる。

プロジェクト作成

$ django-admin startproject core
$ mv core sample_email_login
$ cd sample_email_login

アプリ作成

$ python manage.py startapp account

account/models.py

django.contrib.auth.modelsUserManagerAbstractUser を継承して利用。コピペして必要な箇所を削除・修正するのがラクかも。
(今回は簡単に AbstractUser 使ってるけど実際開発で使う場合は AbastractBaseUser を継承して User 作ると思う。)

account/models.py
from django.contrib.auth.models import AbstractUser, UserManager
from django.db import models
from django.utils.translation import gettext_lazy as _


class UserManager(UserManager):
    def _create_user(self, email, password, **extra_fields):
        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_user(self, email, password=None, **extra_fields):
        extra_fields.setdefault('is_staff', False)
        extra_fields.setdefault('is_superuser', False)
        return self._create_user(email, password, **extra_fields)

    def create_superuser(self, email, password, **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(AbstractUser):
    username = models.CharField(_('username'), max_length=150, blank=True)
    email = models.EmailField(_('email address'), unique=True)

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []
  • UserManager を修正しないと manage.py createsuperuser でエラーになる
  • UserManager から username を削除
  • AbstractUser から username の必須を外して email を必須かつユニークに

account/admin.py

account/admin.py
from django.contrib import admin

from .models import User

admin.site.register(User)

core/settings.py

INSTALLED_APPS = [
     'django.contrib.sessions',
     'django.contrib.messages',
     'django.contrib.staticfiles',
+
+    'account',
 ]


 STATIC_URL = '/static/'
+
+AUTH_USER_MODEL = 'account.User'

マイグレーション

$ python manage.py makemigrations account
$ python manage.py migrate

管理者作成

$ python manage.py createsuperuser

動作確認

$ python manage.py runserver

スクリーンショット 2018-01-19 17.52.46.png

Username ではなく Email になっている


スクリーンショット 2018-01-19 17.53.17.png


スクリーンショット 2018-01-19 17.53.28.png


感想

  • もっとシンプルなやり方あるのかな?
  • AbastractBaseUser を継承するとなったら面倒くさそうかも
  • Djangoはコード追いやすくて良い感じ

参考

35
29
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
35
29

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?