views.py :

def edit(request, news_id): if request.method == 'POST': if form.is_valid(): a = Laba.objects.get(pk=news_id) f = LabaForm(request.POST, instance=a) f.save() return redirect('/LR/') form = LabaForm() return render(request, 'LR/edit.html', {'form': form}) 

This code is called by clicking on the button:

  <form method="post" action="edit/{{result.id}}/">{% csrf_token %}<input type="submit" value="Редактировать данные" /></form> 

Clicking on the button returns an error:

local variable 'form' referenced before assignment

I understand that the error is related to the form = LabaForm() fragment, but I don’t understand how to fix it.

  • Your form is first used if form.is_valid() , and then assigned: form = LabaForm() , no? .. - Alekcvp
  • Yes, right, but it should be the other way around or what? - Konstantin
  • In theory, a value must first be assigned, then a variable is used. - Alekcvp
  • @Konstantin, you first check a non-existent object for validity, and then create an object, of course an error will be issued. - insolor

1 answer 1

 def edit(request, news_id): try: a = Laba.objects.get(pk=news_id) except Lada.DoesNotExist: a = None # тут, либо возвращай что объект не найден if a and request.method == 'POST': form = LabaForm(request.POST, instance=a) if form.is_valid(): form.save() return redirect('/LR/') form = LabaForm() return render(request, 'LR/edit.html', {'form': form}) 
  • Thanks helped, it turns out everything was so simple. - Constantine