0

I have a login and query function like this:

def login_backend(request):
    if request.method == 'POST':
        username = request.POST['username']
        username1 = ''.join(username)
        password = request.POST['password']
        password = ''.join(password)
        password1 = hashlib.sha1(password).hexdigest()
        user = authenticate(username=username1, password=password1)
        global user_id 
        user_id = request.user.id
        if user is None:
            return HttpResponseRedirect('/login_backend/')
        else:
            return HttpResponseRedirect('/overview/')
    else:
        return render_to_response('login_backend.html', context_instance=RequestContext(request))

def show_files(request):
    b = File.objects.get(id=user_id) #Get the user id from session .delete() to use delete
    return render_to_response('index.html',  {'result': b}, context_instance=RequestContext(request)

I am getting this error:

Exception Type: NameError at /overview/
Exception Value: global name 'user_id' is not defined

What am I doing wrong?

4

1 回答 1

1

Doingglobal user_id不会声明全局变量。它只是告诉python这个变量是一个全局范围变量。我不喜欢你试图存储user_id在全局变量中。request.user.id始终使用您的视图访问当前用户 ID 。

你认为的这段代码log_backend也是错误的:

global user_id 
user_id = request.user.id # user does not exists in the request because user was trying to logged in

删除它你不需要它。此外,您还需要这样做login(request, user)authenticate因为authenticate功能只是检查提供的用户名和密码是否正确。

user = authenticate(username=username1, password=password1)
login(request, user)
于 2013-01-14T06:23:24.817 回答