Django - 使用电子邮件登录 [英] Django - Login with Email

查看:43
本文介绍了Django - 使用电子邮件登录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望 django 通过电子邮件而不是用户名对用户进行身份验证.一种方法可以提供电子邮件值作为用户名值,但我不想要那样.原因是,我有一个 url /profile//,因此我不能有一个 url /profile/abcd@gmail.com/.

I want django to authenticate users via email, not via usernames. One way can be providing email value as username value, but I dont want that. Reason being, I've a url /profile/<username>/, hence I cannot have a url /profile/abcd@gmail.com/.

另一个原因是所有电子邮件都是唯一的,但有时会发生用户名已被占用的情况.因此,我将用户名自动创建为 fullName_ID.

Another reason being that all emails are unique, but it happen sometimes that the username is already being taken. Hence I'm auto-creating the username as fullName_ID.

如何更改让 Django 使用电子邮件进行身份验证?

How can I just change let Django authenticate with email?

这就是我创建用户的方式.

This is how I create a user.

username = `abcd28`
user_email = `abcd@gmail.com`
user = User.objects.create_user(username, user_email, user_pass)

我是这样登录的.

email = request.POST['email']
password = request.POST['password']
username = User.objects.get(email=email.lower()).username
user = authenticate(username=username, password=password)
login(request, user)

除了先获取用户名之外,还有其他登录方式吗?

Is there any other of of login apart from getting the username first?

推荐答案

您应该编写自定义身份验证后端.像这样的东西会起作用:

You should write a custom authentication backend. Something like this will work:

from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend

class EmailBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        UserModel = get_user_model()
        try:
            user = UserModel.objects.get(email=username)
        except UserModel.DoesNotExist:
            return None
        else:
            if user.check_password(password):
                return user
        return None

然后,在您的设置中将该后端设置为您的身份验证后端:

Then, set that backend as your auth backend in your settings:

AUTHENTICATION_BACKENDS = ['path.to.auth.module.EmailBackend']

已更新.从 ModelBackend 继承,因为它已经实现了像 get_user() 这样的方法.

Updated. Inherit from ModelBackend as it implements methods like get_user() already.

在此处查看文档:https:///docs.djangoproject.com/en/3.0/topics/auth/customizing/#writing-an-authentication-backend

这篇关于Django - 使用电子邮件登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆