2011-08-18 3 views
0

의 주요 오류가 난이 오류가 점점 계속 :Help! 파이썬

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는 기업 내 데이터베이스입니다 : 여기

프로그래밍의 섹션입니다. 그들은 내가 그들의 속성 (들)

2)하지 중복 게시물

3으로 사업을 검색하는 프로그램) 내가 어떻게 할 수 있도록 노력하고있어 등 이름, 도시, 같은 속성을 가진 개체 키를 사용하려고 시도하기 전에 해당 키가 있는지 확인하십시오. '이름'처럼 액세스를 시도하기 전에 request.GET 사전에 있다면 당신은 확인하지 않은

name = request.GET['name'] 

:

+2

내가 돈 '당신은'이름 '하고 값을 접근 시도하기 전에'도시 '키가 request.GET 사전에 존재하는지 확인하려면 다음 섹션을 변경해야처럼

그래서 그것은 본다 그것이 완전한 코드라고 생각하지 마십시오. '사업. 대상 '이란 무엇입니까? 파이썬을 배우기 위해 사용하는 튜토리얼은 무엇입니까? –

+0

[django MultiValueDictKeyError 오류가 중복 될 수 있습니다. 어떻게 처리합니까?] (http://stackoverflow.com/questions/5895588/django-multivaluedictererror-error-how-do-i-deal-with-it) – Johnsyweb

+0

고통 스럽습니다. 'len (x) <1'을 보는가? 'len (x) == 0'은 더 빠르고 분명합니다. 그리고'not len ​​(x)'는 여전히 더 빠르며 내 의견으로는 명백합니다. 비슷하게,'len (x)> 0'은 더 빠르며'len (x)'만큼 빠릅니다. 그리고'set','list's,'tuple's,'str's 등으로'len()'비트를 버리고'x' 또는'not x' 만 할 수도 있습니다. 그러므로''len (p)> 0과 len (q) <1 :'과 같은 것들은''p가 아닌 q :' '로 할 수 있습니다. 적어도 읽을 때 훨씬 쉬울 것입니다. –

답변

2

그것은 당신이 오류가 될 수있는 유일한 장소처럼 보이는이 라인에 위와 같이 했으므로 키가 요청에 존재하지 않으면 키 오류가 발생합니다 .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