正如我的标题所说,我想知道是否有办法让用户不仅可以使用他的用户名,还可以使用他的用户电子邮件登录。我想标准化登录过程,因为目前我让我的用户使用许多不同的约定并且它变得非常混乱。
问问题
343 次
2 回答
2
如果您强制使用唯一的电子邮件地址,您可能会这样做。这意味着任何用户都不能拥有相同的电子邮件地址。这样,您可以通过电子邮件地址获取用户并登录。
表单可能如下所示:
<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>
view 方法可能看起来像这样:
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
于 2010-11-24T14:24:04.883 回答
0
我想我“解决了”我的问题,至少它现在是功能性的。我决定使用我自己的身份验证后端。我创建了一个文件 'auth_backends.py' 并将其添加到我的 settings.py 中的 AUTHENTICATION_BACKENDS 中:
我的登录表单字段仅包含“用户名”和密码。我要检查输入的用户名是否实际上是他的用户名或电子邮件的唯一方法是执行 .find('@')。有没有更好的方法来检查它?这够了吗?我这样做的全部原因是因为用户更容易记住他/她的电子邮件而不是他的用户名(实际上是一个由数字组成的“id”)。
我还必须处理重复的电子邮件。
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
于 2010-11-24T20:37:05.847 回答