Cannot access local variable 'nr' where it is not associated with a value

def NearByDoc(request):
    if request.method == "POST":
        nearby = request.POST.get("NearBy")
        nr = nearby
    return render(request,'nearbyDoc.html',{'nrb':NearBy_Doctor.objects.all(),'near':nr})

How can I pass "nr" variable to the dictionary? Help me to solve this. I'm new at Django.

I think your error may occur when request.method != "POST", in which condition, nr is not initialized. I think the following changes may be helpful:

def NearByDoc(request):
    nr = None
    if request.method == "POST":
        nearby = request.POST.get("NearBy")
        nr = nearby
    return render(request,'nearbyDoc.html' {'nrb':NearBy_Doctor.objects.all(),'near':nr})

Initialize nr to whatever value you want.

Back to Top