2010-11-24 50 views

回答

2

如果您强制使用唯一的电子邮件地址,则可以这么做。意思是没有用户可以拥有相同的电子邮件地址。这样,您就可以通过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

每个用户确保独特的e-mail地址:http://bit.ly/aOaAbw

+0

这可能有效。我还发现了编写我自己的身份验证后端并将其包含为中间件。 – chiurox 2010-11-24 19:29:27

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 
相关问题