[Fixed]-Django : NameError at /approved/filter/7/ – name 'testElement' is not defined

1👍

class FilterSearch(View):
template_name = ‘approved/approvedElementsSEView.html’

def post(self,request,testPlanId):
    elemType = request.POST.get('testElementType');
    elemCategory = request.POST.get('category');

    if(elemCategory=='routing'):
        testElement = ApprovedTestElement.objects.filter(testElementType=elemType, routing='y');
    if(elemCategory=='switching'):
        testElement = ApprovedTestElement.objects.filter(testElementType=elemType, switching='y');   


    return render(request,self.template_name,{'testElement':testElement,'testPlanId':testPlanId})

0👍

You’l need to handle few more cases.

Case 1:- What if elemCategory is undefined?

Case 2:- What if elemCategory is not ‘routing’ or ‘switching’?

Maybe this will help.

def post(self,request,testPlanId):
    elemType = request.POST.get('testElementType')
    elemCategory = request.POST.get('category')

    if elemCategory:
        if(elemCategory=='routing'):
            testElement = ApprovedTestElement.objects.filter(testElementType=elemType, routing='y')
        if(elemCategory=='switching'):
            testElement = ApprovedTestElement.objects.filter(testElementType=elemType, switching='y')
        if not (elemCategory=='routing' or elemCategory=='switching'):
            testElement = 'Not Found!' #You can change this to your requirement

    else:
        testElement = 'Not Found!' #You can change this to your requirement

    return render(request,self.template_name,{'testElement':testElement,'testPlanId':testPlanId})

Or

def post(self,request,testPlanId):
    elemType = request.POST.get('testElementType')
    elemCategory = request.POST.get('category')
    testElement = 'Not Found!' #You can change this to your requirement

    if elemCategory:
        if(elemCategory=='routing'):
            testElement = ApprovedTestElement.objects.filter(testElementType=elemType, routing='y')
        if(elemCategory=='switching'):
            testElement = ApprovedTestElement.objects.filter(testElementType=elemType, switching='y')

    return render(request,self.template_name,{'testElement':testElement,'testPlanId':testPlanId})

Leave a comment