'User'Object没有attribude is_authenticated

nia*_*loc 5 django middleware django-middleware django-authentication

我为我的django应用程序创建了一个User模型

class User(Model):
    """
    The Authentication model. This contains the user type.  Both Customer and
    Business models refer back to this model.
    """
    email = EmailField(unique=True)
    name = CharField(max_length=50)
    passwd = CharField(max_length=76)
    user_type = CharField(max_length=10, choices=USER_TYPES)
    created_on = DateTimeField(auto_now_add=True)
    last_login = DateTimeField(auto_now=True)

    def __unicode__(self):
        return self.email

    def save(self, *args, **kw):
        # If this is a new account then encrypt the password.
        # Lets not re-encrypt it everytime we save.
        if not self.created_on:
            self.passwd = sha256_crypt.encrypt(self.passwd)
        super(User, self).save(*args, **kw)
Run Code Online (Sandbox Code Playgroud)

我还创建了一个身份验证中间件来使用这个模型.

from accounts.models import User
from passlib.hash import sha256_crypt

class WaitformeAuthBackend(object):
    """
    Authentication backend fo waitforme
    """

    def authenticate(self, email=None, password=None):
        print 'authenticating : ', email
        try:
            user = User.objects.get(email=email)
        except User.DoesNotExist:
            user = None

        if user and sha256_crypt.verify(password, user.passwd):
            return user
        else:
            return None

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None
Run Code Online (Sandbox Code Playgroud)

我已经正确修改了settings.py文件,如果我向这个后端添加一些打印语句,我可以看到打印出的用户详细信息.我不记得读过我需要在django文档中实现is_authenticated.我错过了一些傻事吗?

Dan*_*man 5

我不太确定为什么您创建了一个新的User模型,而不是使用Django的内置模型并添加链接的UserProfile,这是推荐做的事情(直到1.5发行,当可插入用户模型可用时)。但是,是的,您需要定义一个is_authenticated方法,该方法始终返回True:这正是内置模型所做的。原因是,如果您有一个实际的User,则将始终对其进行身份验证:否则,您将具有AnonymousUser对象,该对象的is_authenticated方法始终返回False。