如何获取login()在会话中保存的用户对象?
user= request.session.get('user')
在此示例中不返回任何内容:
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
答案 0 :(得分:2)
确保已安装的应用中包含“django.contrib.auth
”和“django.contrib.contenttypes
”。如果需要,请运行syncdb。现在,您将拥有所需的所有用户表。
接下来,您要确保每个请求都有request.user。我想这就是为什么你没有得到任何request.user。 SessionMiddleware
和AuthenticationMiddleware
个中间件需要位于MIDDLEWARE_CLASSES
设置中。
有关详细信息,请阅读文档here
答案 1 :(得分:-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