Django 1.10 - 如何将前端用户身份验证从用户名更改为电子邮件?

时间:2016-11-22 10:17:03

标签: python django authentication

Django中,默认用户身份验证通过UsernamePassword进行了整合。在我的项目个人资料页面中,我可以选择更改Username。因此,有必要使用emailpassword在后​​端和前端更改我的身份验证系统。

使用authentication backend我可以通过管理员中的emailpassword更改默认身份验证系统。这是代码 -

class EmailBackend(object):
    def authenticate(self, username=None, password=None, **kwargs):
        UserModel = get_user_model()
        try:
            user = UserModel.objects.get(email=username)
        except UserModel.DoesNotExist:
            return None
        else:
            if getattr(user, 'is_active', False) and  user.check_password(password):
                return user
        return None

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

settings.py -

AUTHENTICATION_BACKENDS = (
    'apps.account.email-auth.EmailBackend',
)

我想知道如何通过前端进行身份验证。我已经通过emailpassword准备了正面登录页面。

但请参阅form.errors并预测必须丢失任何前身身份验证,例如AUTHENTICATION_BACKENDS

非常感谢你的帮助!

2 个答案:

答案 0 :(得分:1)

实际上答案在方法范围内 -

def authenticate(self, username=None, password=None, **kwargs):

在前端,使用email命名用户输入将不会在方法中传递,然后表单错误显示与不匹配的凭据。因此,只需将输入作为username即可解决问题。

答案 1 :(得分:0)

有一个包django-allauth。它处理身份验证。 它允许使用'电子邮件'和密码'或者'用户名'和密码'用于身份验证它包括表格和所需的一切。 Django-cookiecutter项目模板使用此包来处理身份验证,因此您可以查看并将其用作示例。