Django的:更改/允许用户登录的用户名也使用他/她的电子邮件
-
28-09-2019 - |
题
正如我的标题所说,我想知道,如果我有一个办法可以让用户不仅使用自己的用户名,也是他的用户的电子邮件登录。我想因为此刻我有我的用户使用许多不同的约定来规范登录过程和它变得相当混乱。
解决方案
您也许可以做到这一点,如果你执行不同的电子邮件地址。这意味着任何用户都不能有相同的E-mail地址。这样,您就可以通过e-mail地址,获取用户和记录它们。
在形式看起来是这样的:
<form method="post" action="{% url myproject.views.login %}">
<p>Username</p>
<input type='text' name='username'/>
<p>Password</p>
<input type='password' name='password'/>
<input type="submit" value="Login"/>
</form>
视图方法可能看起来像这样:
def login( request ):
username = request.POST['username']
password = request.POST['password']
user = User.objects.filter( email = username )[0]
if( user is not None ):
# -- the user was retrieved by an email address
# -- now you can authenticate and log them in log them in
from django.contrib import auth
user = auth.authenticate( user.username, password )
if( user is not None ):
auth.login( user, request )
OpenID的可能是另一种方式去: http://bit.ly/a2OlHX
确保每个用户唯一的电子邮件地址: http://bit.ly/aOaAbw
其他提示
我想我“解决”我的问题,至少它的功能,现在。 我决定用我自己的认证后端。我创建的文件“auth_backends.py”和在我的settings.py它加入到AUTHENTICATION_BACKENDS:
我的登录表单字段仅包含“用户名”和密码。我做检查,如果输入的用户名,其实是他的用户名或电子邮件的唯一途径,就是通过做.find(“@”)。 有没有更好的方法来检查呢?这是否足够? 整个原因,我做的,这是因为它的用户更容易记住他/她的电子邮件比他的用户名(这实际上是一个“身份证”为由数字)。
我也不得不采取重复的电子邮件的照顾。
from django.conf import settings
from django.contrib.auth.backends import ModelBackend
from django.core.exceptions import ImproperlyConfigured
from django.db.models import get_model
from django.contrib.auth.models import User
class CustomUserModelBackend(ModelBackend):
def authenticate(self, **credentials):
if 'username' in credentials:
if credentials['username'].find('@') > 0:
return self.authenticate_by_email(**credentials)
else:
return self.authenticate_by_username(**credentials)
def authenticate_by_username(self, username=None, password=None):
try:
user = User.objects.get(username=username)
if user.check_password(password):
return user
except User.DoesNotExist:
return None
def authenticate_by_email(self, username=None, password=None):
try:
user = User.objects.get(email=username)
if user.check_password(password):
return user
except User.DoesNotExist:
return None
不隶属于 StackOverflow