1

如何获取 login() 在会话中保存的用户对象?

user= request.session.get('user') 

什么都不返回在这个例子中:

user = authenticate(username=username, password=password)
if user is not None:
    if user.is_active:
        login(request, user)
4

2 回答 2

2

确保您已安装的应用程序中有“ django.contrib.auth”和“ django.contrib.contenttypes”。之后如果需要运行syncdb。现在您将拥有所需的所有用户表。

接下来,您要确保每个请求都有 request.user 。我认为这就是为什么你没有得到任何 request.user 的原因。 SessionMiddleware并且AuthenticationMiddleware中间件需要在您MIDDLEWARE_CLASSES的设置中。

有关更多信息,请阅读此处的文档

于 2013-04-18T20:19:10.590 回答
-2

AuthenticationMiddleware将代表当前登录用户的用户属性添加到每个传入的 HttpRequest 对象。身份验证中间件需要安装会话中间件。因此,您应该在 settings.py 中将此中间件添加到 MIDDLEWARE_CLASSES 元组:

MIDDLEWARE_CLASSES = ( 
    #...
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    #...
)

顺便说一句,如果你想知道这个中间件从哪里获得用户,请查看 auth 中间件源:

# contrib.auth.middleware.py:

def get_user(request):
    if not hasattr(request, '_cached_user'):
        request._cached_user = auth.get_user(request)
    return request._cached_user

class AuthenticationMiddleware(object):
    def process_request(self, request): 
        assert hasattr(request, 'session'), "The Django authentication middleware requires session middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.sessions.middleware.SessionMiddleware'."

        request.user = SimpleLazyObject(lambda: get_user(request))


# django.contrib.auth.__init__.py (auth.get_user)

def get_user(request):
    from django.contrib.auth.models import AnonymousUser
    try:
        user_id = request.session[SESSION_KEY]
        backend_path = request.session[BACKEND_SESSION_KEY]
        backend = load_backend(backend_path)
        user = backend.get_user(user_id) or AnonymousUser()
    except KeyError:
        user = AnonymousUser()
    return user

和默认 backend.get_user:

# contrib.auth.backends.py

def get_user(self, user_id):    
    try:
        return User.objects.get(pk=user_id)
    except User.DoesNotExist:       
        return None
于 2013-04-18T20:13:40.233 回答