local variable 'nextofkin' referenced before assignment

Hi! Everything was working fine until when i added the try and catch block, this ‘unboundLocalErro’ occurs. I check whether the variable tally with my models objects but not. I checked my indentation but everything is ok. Please I need help.

def  nextofkinupdate(request, id):
    try:
        nextofkin = Next_of_kin.objects.get(user_id = id)
    except Next_of_kin.DoesNotExist:
        messages.error(request, 'You most save next of kin first!!')
    
    if request.method =='POST':
        form =nextofkinForm(request.POST, instance =nextofkin)
        if form.is_valid:

            form.instance.user = request.user 
            form.save() 
            
            messages.success(request, 'Your next of kin is Updated! Move to the next step')
            return redirect('nextofkin')
            
        messages.error(request, 'Invalid')
        return render(request,'portal/home/nextofkinupdate.html')
    
    else:
        form =nextofkinForm(instance = nextofkin)
    context = {
        'form':form,
      }
    return render(request,'portal/home/nextofkin.html', context)

Traceback

  Microsoft Windows [Version 6.3.9600]
  (c) 2013 Microsoft Corporation. All rights reserved.
  
  C:\Users\Christopher\adamawa_civil_service_recruitment>python manage.py runserver
  Watching for file changes with StatReloader
  Performing system checks...
  
  System check identified no issues (0 silenced).
  November 16, 2022 - 12:43:36
  Django version 4.0, using settings 'adamawa_civil_service_recruitment.settings'
  Starting development server at http://127.0.0.1:8000/
  Quit the server with CTRL-BREAK.
  Internal Server Error: /nextofkinupdate/2/
  Traceback (most recent call last):
    File "C:\Users\Christopher\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
      response = get_response(request)
    File "C:\Users\Christopher\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
      response = wrapped_callback(request, *callback_args, **callback_kwargs)
    File "C:\Users\Christopher\adamawa_civil_service_recruitment\portal\views.py", line 96, in nextofkinupdate
      form =nextofkinForm(instance = nextofkin)
  UnboundLocalError: local variable 'nextofkin' referenced before assignment
  [16/Nov/2022 12:43:46] "GET /nextofkinupdate/2/ HTTP/1.1" 500 63237


class Next_of_kin(models.Model):
    user=models.ForeignKey(User, null=True, on_delete=models.CASCADE)
    name=models.CharField(max_length=100, null=True)
    email =models.EmailField(max_length=100, null=True)
    phone= models.CharField(max_length=15)
    contact_address =models.CharField(max_length=300, null = True)

    def __str__(self):
        return self.name

If this exception is triggered, there is no assignment to a variable named nextofkin. Therefore, there is no variable by that name when you enter the if request.method ... block.

Ok. So what is the solution? Because i need that exception.

The solution depends, on what you want to achieve.
Normally in this scenario your render the template again, redirect the user.
But if you still want to keep processing with this, you may set nextofkin to None on the except block.

Thanks. It worked! I set the nextofkin variable to None