user1881957
user1881957

Reputation: 3378

Global name user_id not defined in Django?

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?

Upvotes: 0

Views: 1658

Answers (1)

Aamir Rind
Aamir Rind

Reputation: 39659

Doing global user_id does not declare a global variable. It just tell python that this variable is a global scope variable. I don't like that you are trying to store user_id in global variable. Always access the current user id using request.user.id in your view.

This piece of code in your log_backend view is also wrong:

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

Just remove it you don't need it. Also you need to do login(request, user) after authenticate because authenticate function is just to check username and password supplied is correct.

user = authenticate(username=username1, password=password1)
login(request, user)

Upvotes: 1

Related Questions