'im getting "variable has been referenced before intialization" error at the last line in django framework [closed]

def result(request):
    check = None
    try:
        check = user_answers.objects.get(username=request.session["username"])
    except:
        check = None
    if check:
        results,a1,a2,a3,a4,a5 = getPredictions(check)
        username = request.session["username"]
        ans = clusterNum.objects.create(username_id=request.session["username"],clusNo =             results[0],extroversion=a1,neurotic=a2,agreeable=a3,conscientious=a4,openness=a5)
        ans.save()
        
    # results = getPredictions()
    return render(request,'result.html',{'name':username,'a1':a1,'a2':a2,'a3':a3,'a4':a4,'a5':a5})

i tried converting them to global but the result is not as expected,it show no values in the webpage

Traceback (most recent call last):

File "D:\Django\predictor\Personality\views.py", line 230, in result
return render(request,'result.html', 
{'name':username,'a1':a1,'a2':a2,'a3':a3,'a4':a4,'a5':a5})

Exception Type: UnboundLocalError at /personality/result
Exception Value: local variable 'results' referenced before 
assignment


Solution 1:[1]

In this code, the variables only get values inside the 'if check:' clause. In other words, when this line of code raises an exception:

check = user_answers.objects.get(username=request.session["username"])

or when the check variable has a negative value (False, 0, None, empty list...), the interpreter doesn't get inside the 'if check:' clause. Therefore your variables (username, a1 ...) don't "exist". Yet they are called on the last line.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 schalouh