有没有办法使用用户名或电子邮件登录Django管理界面?

时间:2019-07-08 08:43:01

标签: python django web django-rest-framework web-site-project

我想实现一个登录系统,以通过电子邮件或用户名登录Django admin。有谁知道如何实现它。我使用自定义用户模型。我知道如何允许用户使用用户名或电子邮件登录网站。但这在Django管理界面中不起作用

from django.conf import settings
from django.contrib.auth import get_user_model


class EmailOrUsernameModelBackend(object):

    def authenticate(self, username=None, password=None):
        if '@' in username:
            kwargs = {'email': username}
        else:
            kwargs = {'username': username}
        try:
            user = get_user_model().objects.get(**kwargs)
            if user.check_password(password):
                return user
        except User.DoesNotExist:
            return None

    def get_user(self, username):
        try:
            return get_user_model().objects.get(pk=username)
        except get_user_model().DoesNotExist:
            return None

1 个答案:

答案 0 :(得分:1)

您需要通过authenticated方法传递请求:

from django.conf import settings
from django.contrib.auth import get_user_model


class EmailOrUsernameModelBackend(object):

    def authenticate(self, request, username=None, password=None):
        if '@' in username:
            kwargs = {'email__iexact': username}
        else:
            kwargs = {'username': username}
        try:
            user = get_user_model().objects.get(**kwargs)
            if user.check_password(password):
                return user
        except User.DoesNotExist:
            return None

    def get_user(self, username):
        try:
            return get_user_model().objects.get(pk=username)
        except get_user_model().DoesNotExist:
            return None

此外,请确保将其放入AUTHENTICATION_BACKENDS

AUTHENTICATION_BACKENDS = ['path.to.EmailOrUsernameModelBackend']