40pro
40pro

Reputation: 1281

Python scope of variable -referenced before assignment error

Error Produced

local variable 'url' referenced before assignment

I have searched for this issue in SO but most of them seem to address the fact that the variable is declared outside the function and needed to be globalized or the variable is being accessed in a member function of a class. This case is different. I don't understand why I am not allowed to call url inside the same function.

Looking at the code below, wouldn't url be accessible in anywhere inside login function? I believe if this is C/C++ that would be the case. Why is this any different?

Code

def login(request):
  #  
  #no url declaration here
  #
  if request.POST:
     …
    url = 'main.login.html'
    user = authenticate(username=username,password=password)
    if user is not None:
        if user.is_active:
            auth_login(request, user)
            state = 'You are logged in'
            url = 'main.home.html'
        else:
            state = 'You are not logged in due to error'
    else:
        state = 'Incorrect username or password'

    …
 render_to_response(url,{'state':state,'username':username},context_instance=RequestContext(request)

Traceback points to the last line.

render_to_response(url,{'state':state,'username':username},context_instance=RequestContext(request)

Upvotes: 0

Views: 383

Answers (1)

Ankit Mittal
Ankit Mittal

Reputation: 672

In your code, you made two change and it will work fine. Define url before checking post method and use return keyword with render_to_response statement.

def login(request):
  url = 'main.login.html'
  state = ''
  if request.POST:
    user = authenticate(username=username,password=password)
    if user is not None:
        if user.is_active:
            auth_login(request, user)
            state = 'You are logged in'
            url = 'main.home.html'
        else:
            state = 'You are not logged in due to error'
    else:
        state = 'Incorrect username or password'

 return render_to_response(url,{'state':state,'username':username},context_instance=RequestContext(request)

If you do not define url and state before checking POST method, then it will raise error for GET request.

Upvotes: 2

Related Questions