0
1

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 1 year has passed since last update.

DjangoのCustomUserModelでログインができないバグを解消した

Posted at

DjangoでCustomUserModelを定義後、ログインの時のis_validができなかった

nameというフィールドを持った単純なCustomUserというモデルをAbstractUserを継承することで定義しました。

class CustomUser(AbstractUser):
    name = models.CharField(max_length=30)
    groups = models.ManyToManyField(
        'auth.Group',
        related_name='custom_user_set',
        blank=True,
        help_text='The groups this user belongs to.'
    )
    user_permissions = models.ManyToManyField(
        'auth.Permission',
        related_name='custom_user_set',
        blank=True,
        help_text='Specific permissions for this user.'
    )

サインアップ(form.save)は実行できアカウントが作れることを確認後、ログインするためのLoginForm.is_valid()がFalseになってしまいログインができなくなっていました。

解決策

CustomUserを作成したら

  • アプリ名/backends.pyの作成
  • settigns.pyのAUTHENTICATION_BACKENDSの記載
    が必要でした。

アプリ名/backends.pyの作成


BaseBackendというのを継承してauthenticateを作成したCustomUserモデルに適した形に定義する必要がありました。

from django.contrib.auth.backends import BaseBackend
from .models import CustomUser

class CustomUserBackend(BaseBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            user = CustomUser.objects.get(username=username)
        except CustomUser.DoesNotExist:
            return None

        if user.check_password(password):
            return user

        return None

settings.pyの書き換え

先ほど適用させたbackendの情報をsettings.pyに記載して読み込んでもらう必要がありました。

# autheticationをカスタムユーザーモデルに適応させる
AUTHENTICATION_BACKENDS = [
    'django.contrib.auth.backends.ModelBackend',
    'polls.backends.CustomUserBackend',  # カスタムユーザーモデルのバックエンドを指定
]

これで私のプログラムは正しくis_valid()でTrueが返ってくるようになりましたので参考になれば幸いです。

0
1
0

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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?