6
votes

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?

2
Please include the full traceback, it will well you what line the problem is happening on. - Ross Patterson
is the indentation correct in your code sample? - steabert

2 Answers

14
votes

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.

7
votes

You almost certainly want to de-indent this part:

else:
    form = AddClientForm()

That is, on the initial GET of the page, use a blank client form, then when the page is POSTed, use the request POST data to fill in the form object.