1
def login_user(request):
    if request.session['member_id']:
        m=User.objects.get(id=request.session['member_id'])
        #state = "You're successfully logged in!"
        username = m.username
        return render(request,'auth/success.html',{'username': username})
    else:    
        state = "Please log in below..."
        username = password = ''
        if request.POST:
            username = request.POST.get('username')
            password = request.POST.get('password')

            user = authenticate(username=username, password=password)
            if user is not None:
                if user.is_active:
                    login(request, user)
                    m=User.objects.get(username=username)
                    state = "You're successfully logged in!"
                    request.session['member_id'] = m.id
                    return render(request,'auth/success.html',{'state':state, 'username': username})
                else:
                    state = "Your account is not active, please contact the site admin."
                    return render(request,'auth/auth.html',{'state':state, 'username': username})
            else:
                state = "Your username and/or password were incorrect."
                return render(request,'auth/auth.html',{'state':state, 'username': username})

        else:
            return render(request,'auth/auth.html',{'state':state, 'username': username})

我的代码和上面一样。实际上我想检查 session 中是否存在 member_id。但是在 member_id 的 login_user 函数视图中获取 KeyError

4

1 回答 1

2

您应该使用in运算符

if 'member_id' in request.session:

请注意,如果它存在,但“虚假”(FalseNone、等),则0运算符将成功,但不会是有效的,因此您可能需要同时检查两者:""inrequest.session['member_id']id

if 'member_id' in request.session and request.session['member_id']:
于 2013-02-23T20:21:40.347 回答