我是Django的新手,我試圖根據if語句滿足而發送不同的上下文變量。這是我的看法:Django:NameError at/approved/filter/7/- name'testElement'未定義
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'):
global testElement;
testElement=ApprovedTestElement.objects.filter(testElementType=elemType, routing='y');
return testElement
elif(elemCategory=='switching'):
global testElement;
testElement = ApprovedTestElement.objects.filter(testElementType=elemType, switching='y');
return testElement
return render(request,self.template_name,{'testElement':testElement,'testPlanId':testPlanId})
我最初得到一個UnboundLocalError:局部變量「testElement」引用之前分配,我試圖通過定義testElement作爲一個全局變量固定,現在我得到一個NameError:名字「testElement ' 沒有定義。任何幫助將不勝感激!
如果沒有'if' /'elif'是真的會發生什麼?順便說一下,行尾的';'不是必需的,並且條件周圍的括號也不是必需的(儘管它們不影響錯誤)。 – cdarke
Global在這裏不是正確的解決方案;你不應該隨意使用它來解決名稱錯誤。你爲什麼要在if和elif裏面以及在方法結尾返回? –
謝謝!我做了上述修改並刪除了elif,現在它可以工作。 –