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?
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.
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.
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.
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.
This is what is happening:
if
block is not being entered.form
variable is not defined.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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With