从不同的视图访问时,Django request.user变为匿名

时间:2013-01-31 18:25:32

标签: django request

我在此视图中验证用户身份:

def note_edit_auth(request):
        if request.method == 'POST':
                form = EditAuthForm(request.POST)
                if form.is_valid():
                        email = form.cleaned_data['email']
                        password = form.cleaned_data['password']
                        user = auth.authenticate(username = email, password = password)

                        if user and user.is_authenticated():
                                request.session['email'] = email
                                request.session['password'] = password
                                request.session['user'] = user
                                return HttpResponseRedirect('/note_edit')
                        else:
                                return HttpResponse('User or password is either incorrect or does not exist.')

它有效。 user确实已经过身份验证。那么我尝试从另一个视图访问request.user,其中上面的视图重定向到这样:

def note_edit(request):
        if request.method == 'POST' and request.user.is_authenticated():
                form_edit = EditForm(request.POST)
                user = request.session['email']
                auth.logout(request)
                return HttpResponse('Done!')
        elif request.method == 'GET' and request.user.is_authenticated():
                form_edit = EditForm(irrelevantfoofoo)
        else:
                return HttpResponse('User not authenticated.')
        return render_to_response('editnote.htm', {'form': form_edit}, context_instance = RequestContext(request))

突然间我收到用户未经过身份验证的响应。当我尝试将request.user打印到控制台时,它显示为AnonymousUser。我告诉你,这不是昨晚工作正常。今天我醒来,做了一些改变,开始行为不端。我恢复了所有的变化,但仍然行为不端。

为什么会发生这种情况,我该如何解决?

1 个答案:

答案 0 :(得分:0)

auth.authenticate()只检查提供的用户凭据是否有效。 要实际登录用户,必须使用login()