首页 文章

Django登录(请求,用户)不要将用户置于会话中?

提问于
浏览
0

我似乎无法弄清楚如何在Django中登录用户 . 我很困惑,因为文档明确告诉你如何做到这一点,但仍然不知何故我一定是犯了错误 .

链接https://docs.djangoproject.com/en/dev/topics/auth/default/#django.contrib.auth.login说"To log a user in, from a view, use login(). It takes an HttpRequest object and a User object. login() saves the user’s ID in the session, using Django’s session framework."

所以我有以下views.py:

def login_view(request):
    if request.method == 'GET':
        return render(request, 'app/login.htm')
    if request.method == 'POST':
        username = request.POST.get('username', '')
        password = request.POST.get('password', '')
        user = auth.authenticate(username=username, password=password)
        if user is None:
            return HttpResponseRedirect(reverse('error'))
        if not user.is_active:
            return HttpResponseRedirect(reverse('error'))

        # Correct password, and the user is marked "active"
        auth.login(request, user)
        # Redirect to a success page.
        return HttpResponseRedirect(reverse('home'))

def home(request):
    contextdict = {}
    if request.session.user.is_authenticated():
        contextdict['username'] = request.session.user.username
    context = RequestContext(request, contextdict )
    return render(request, 'app/home.htm', context)

现在,通过使用print'qqq',我知道'is None'和'not is_active'已被评估为True,因此评估auth.login并返回HttpResponseRedirect . 我希望Everythin正常运行并且用户登录,并且用户名将作为主页视图中的上下文传递 . 但是,Django给了我以下错误:

AttributeError at /app/home/
'SessionStore' object has no attribute 'user'

是的,我不知道我在做什么 .

1 回答

  • 4

    您应该使用 request.user 来获取用户对象,而不是 request.session.user .

    会话中的数据用于检索用户对象,但会话不包含实际用户

相关问题