2011-08-18 57 views
0

關鍵的錯誤,我不斷收到此錯誤:幫助!在python

MultiValueDictKeyError at /search/ 

"Key 'name' not found in <'QueryDict: {}>" 

我剛開始學習編程,前兩天,所以有人可以通俗地說解釋爲什麼有一個問題,以及如何解決它。謝謝!

這裏是編程的部分:

def NameAndOrCity(request): 
    NoEntry = False 
    if 'name' in request.GET and request.GET['name']: 
     name = request.GET['name'] 
     if len(Business.objects.filter(name__icontains=name)) > 0: 
      ByName = Business.objects.filter(name__icontains=name) 
      q = set(ByName) 
      del ByName 
      ByName = q 

    if 'city' in request.GET and request.GET['city']: 
     city = request.GET['city'] 
     if len(Business.objects.filter(city__icontains=city)) > 0: 
      ByCity = Business.objects.filter(city__contains=city) 
      p = set(ByCity) 
      del ByCity 
      ByCity = p 


    if len(q) > 0 and len(p) > 0: 
      NameXCity = q & p 
      return render_to_response('search_results.html', {'businesses':NameXCity, 'query':name}) 
     if len(q) > 0 and len(p) < 1: 
      return render_to_response('search_results.html', {'businesses':ByName, 'query':name}) 
     if len(p) > 0 and len(q) < 1: 
      return render_to_response('search_results.html', {'businesses':ByCity, 'query':city}) 
     else: 
      NoResults = True 
      return render_to_response('search_form.html', {'NoResults': NoResults}) 
    else: 
     name = request.GET['name'] 
     city = request.GET['city'] 
     if len(name) < 1 and len(city) < 1: 
      NoEntry = True 
     return render_to_response('search_form.html', {'NoEntry': NoEntry}) 

編輯

1)Business.object是我的企業數據庫。它們與如姓名,城市等屬性,我試圖讓一個程序,將通過他們的屬性(S)

2)不重複的職位

3搜索業務),我該怎麼辦的對象在我嘗試使用它們之前檢查這些密鑰是否存在?

+2

我不我認爲這是你的完整代碼。什麼是'Business.objects'?你正在使用哪個教程來學習Python? –

+0

可能重複[django MultiValueDictKeyError錯誤,我該如何處理它](http://stackoverflow.com/questions/5895588/django-multivaluedictkeyerror-error-how-do-i-deal-with-it) – Johnsyweb

+0

這很痛苦看到'len(x)<1'? 'len(x)== 0'更快,更明顯,'不len(x)'更快,在我看來也是如此。同樣,'len(x)> 0'越快越好,就像'len(x)'一樣。並且使用'set's,'list's,'tuple's,'str's等等,你甚至可以放下'len()'位,只是做'x'或'not x'。因此,如果len(p)> 0和len(q)<1:'可以做成'if p and not q',那麼我至少會發現它更容易閱讀。 –

回答

2

它看起來像你可能會收到此錯誤的唯一地方是在這條線:

name = request.GET['name'] 

你沒有檢查,如果「名」在字典request.GET中嘗試訪問它像以前一樣你在上面做過,所以你會得到一個關鍵的錯誤,如果該關鍵字不存在request.GET。

所以它看起來像您需要更改以下部分,檢查「名稱」和「城市」鍵在字典request.GET中存在您嘗試訪問該值之前:

name = request.GET['name'] 
city = request.GET['city'] 
if len(name) < 1 and len(city) < 1: 
    NoEntry = True 
return render_to_response('search_form.html', {'NoEntry': NoEntry}) 
+0

'NoEntry = not(name or city)'表示如果'name'或'city'不爲空,否則'NoEntry'將爲'False',否則爲'True'。這樣做更短(我不是說更清潔)的方式。 – Tadeck