2011-08-18 97 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