简体   繁体   中英

I am getting the error that the local variable cruty referenced before assignment

Getting the error local variable 'cruty' referenced before assignment

def index(request):
    if request.method =="POST":
        fname= request.POST.get("fname",None)
        if fname is not None:
            dname= Students.objects.get(USN=fname)
            print(dname)
            cruty= Marks.objects.filter(students=dname)
            print(cruty)
    return render(request, "index.html", {"cruty": cruty})
def index(request):
    if request.method =="POST":
        cruty = None
        fname = request.POST.get("fname",None)
        if fname is not None:
            dname= Students.objects.get(USN=fname)
            print(dname)
            cruty= Marks.objects.filter(students=dname)
            print(cruty)
        return render(request, "index.html", {"cruty": cruty})

Always make sure that the variable you are accessing is in the scope of the block of code, eg you are trying to access cruty outside the

if fname is not None

condition, but cruty is not visible in return, so you can define the variable in that scope, and that would work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM