Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Local Variable referenced before assignment

I was wondering if you guys could help. I'm trying to do a simple view where it sends the user to the client creation form, but I keep getting this error:

local variable 'form' referenced before assignment

Looking at my code, I can't see whats wrong.

def add_client(request):
    user = request.user
    if request.method =='POST':
        form = AddClientForm(request.POST)
        if form.is_valid():
            client = form.save(commit=False)
            client.save()
            return HttpResponseRedirect('/')
        else:
            form = AddClientForm()

    return render_to_response('clients/addClient.html', { 'form': form, 'user': user, }, context_instance=RequestContext(request))

Anyone tell me where I went wrong?

like image 496
TheLifeOfSteve Avatar asked Aug 29 '11 19:08

TheLifeOfSteve


People also ask

How do you deal with UnboundLocalError?

UnboundLocalError can be solved by changing the scope of the variable which is complaining. You need to explicitly declare the variable global. Variable x's scope in function printx is global. You can verify the same by printing the value of x in terminal and it will be 6.

What is global function in Python?

In the programming world, a global variable in Python means having a scope throughout the program, i.e., a global variable value is accessible throughout the program unless shadowed. A global variable in Python is often declared as the top of the program.

How do you assign a local variable?

local - Assign a local variable in a function qsh uses dynamic scoping, so that if you make the variable alpha local to function foo, which then calls function bar, references to the variable alpha made inside bar will refer to the variable declared inside foo, not to the global variable named alpha.

What is non local in Python?

The nonlocal keyword is used to work with variables inside nested functions, where the variable should not belong to the inner function. Use the keyword nonlocal to declare that the variable is not local.


1 Answers

This is what is happening:

  1. The if block is not being entered.
  2. The form variable is not defined.
  3. You then attempt to refer to the form variable in the return statement.

As to how to fix it, that's really for you to decide. What the fix is depends on what you want your code to do in case the request method is not POST.

like image 194
David Heffernan Avatar answered Sep 24 '22 23:09

David Heffernan