Local variable referenced before assignment

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

local variable "form" specified before assignment

Looking at my code, I do not see what is 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)) 

Will someone tell me where I was wrong?

+4
source share
2 answers

This is what happens:

  • The if block if not entered.
  • The form variable is undefined.
  • Then you try to access the form variable in the return .

As for how to fix this, you really need to decide. Which fix depends on what you want your code to execute if the request method is not POST .

+13
source

You almost certainly want to undo this part:

 else: form = AddClientForm() 

That is, on the initial GET page, use an empty client form, and then, when the page is POSTED, use the POST request data to fill out the form object.

+7
source

Source: https://habr.com/ru/post/1369554/


All Articles