Django - 用电子邮件登录 [英] Django - Login with Email
问题描述
我想要django通过电子邮件验证用户,而不是通过用户名。一种方式可以提供电子邮件价值作为用户名,但我不想要。原因是,我有一个网址 / profile /< username> /
,因此我不能有一个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
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
然后,将后端设置为您的身份验证后端您的设置:
Then, set that backend as your auth backend in your settings:
AUTHENTICATION_BACKENDS = ['path.to.auth.module.EmailBackend']
这篇关于Django - 用电子邮件登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!