Reputation: 177
I keep getting this error:
MultiValueDictKeyError at /search/
"Key 'name' not found in <'QueryDict: {}>"
I just started learning programming two days ago, so can someone explain in layman's terms why there's a problem and how to solve it. Thanks!
Here is the section of programming:
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})
EDIT
1) Business.object is my database of businesses. They are objects with attributes like name, city, etc. I'm trying to make a program that will search the businesses by their attribute(s)
2) not a duplicate post
3) how do I check to see if those keys exist before I try to use them?
Upvotes: 0
Views: 1138
Reputation: 3706
It looks like the only place you could be getting this error is on this line:
name = request.GET['name']
You haven't checked if 'name' is in the request.GET dictionary before trying to access it like you did above so you will get a key error if that key doesn't exist in request.GET.
So it looks like you need to change the following section to check if the 'name' and 'city' keys exist in your request.GET dictionary before you try accessing the values:
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})
Upvotes: 2