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?
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})
Related
I have a code which first sorts the emails into alphabetical order and then attempts to use binary search to search a user inputted email from a list. However, I have been stuck on how to do this for so long and haven't found any solutions on the error I get and how to fix it. Here is my code
def BubbleSort(logindata):
NoSwaps = 1
N = len(logindata)
logindata = list(logindata)
while NoSwaps == 1:
Count = 1
NoSwaps = 0
for Count in range(N-1):
if logindata[Count] > logindata[Count+1]:
temp = logindata[Count]
logindata[Count] = logindata[Count+1]
logindata[Count+1]=temp
NoSwaps=1
return tuple(logindata)
def BinarySearch(logindata,ItemSought):
First=0
Last=len(logindata)-1
ItemFound = False
SearchFailed = False
while ItemFound == False or SearchFailed == False:
Midpoint = (First + Last) // 2
if logindata[Midpoint] == ItemSought:
ItemFound = True
print("Item Found")
break
elif logindata[Midpoint] > ItemSought:
Last = Midpoint - 1
else:
First = Midpoint + 1
if __name__ == "__main__":
logindata=["tom#gmail.com","Password1"],["harry#gmail.com","Password2"],["jake#gmail.com","Password3"]
logindata=BubbleSort(logindata)
print(logindata)
ItemSought=input("Enter username")
BinarySearch(logindata,ItemSought)
The error I currently get is :
elif logindata[Midpoint] > ItemSought:
TypeError: unorderable types: list() > str()
You're comparing a username/password pair (e.g. ["tom#gmail.com","Password1"]) with a username (e.g. "tom#gmail.com").
You need to extract the username from logindata[Midpoint] before comparing it to ItemSought.
I am new to this, and I am looking for help. I currently am stuck in a program I'm trying to complete. Here it is:
def searchStock(stockList, stockPrice, s):
for i in range(len(stockList)):
if s == stockList[i]:
s = stockPrice[i]
elif s != stockList[i]:
s = -1
return s
def mainFun():
stockList= []
stockPrice = []
l = 1
while l > 0:
stocks = str(input("Enter the name of the stock:"))
stockList += [stocks]
if stocks == "done"or stocks == 'done':
l = l * -1
stockList.remove("done")
else:
price = int(input("Enter the price of the stock:"))
stockPrice += [price]
l = l + 1
print(stockList)
print(stockPrice)
s = input("Enter the name of the stock you're looking for:")
s = searchStock(stockList, stockPrice, s)
Every time I run the program to the end, it never returns the variable s for some reason. If i replace return with print, it always prints -1 instead of the stockPrice if its on the list. I cant seem to get it to work. Can someone please help me?
Try adding this print to help you debug:
def searchStock(stockList, stockPrice, s):
output = -1
for i in range(len(stockList)):
if s == stockList[i]:
output = stockPrice[i]
print i, output, stockList[i], stockPrice[i]
elif s != stockList[i]:
output = -1
return output
Also I changed one of your variables, it seems better than modifying your input value and then returning it.
I need to dynamically generate uniqe username during user's registartion.
Algorithm:
when user's full name is "John Doe" username should be "jdoe" (if available).
If not, it should generate jdoe1, jdoe2 and so until username will be available.
Any exisiting simple solution for this?
def generate_username(first_name,last_name):
val = "{0}{1}".format(first_name[0],last_name).lower()
x=0
while True:
if x == 0 and User.objects.filter(username=val).count() == 0:
return val
else:
new_val = "{0}{1}".format(val,x)
if User.objects.filter(username=new_val).count() == 0:
return new_val
x += 1
if x > 1000000:
raise Exception("Name is super popular!")
Good day friends!
Tell me please, I have the following code:
all_users = UserProfile.objects.all()
for s,usera in enumerate(all_users):
name = usera.nickname
name_id = usera.id
print(s)
if int(s) <= 50:
print('1_iterator')
r = api.request(example)
elif int(s) <= 100:
r = api2.request(example)
elif #a total of seven compounds, api3,api4,api5,api6,api7
try:
for item in r.get_iterator():
#then loop adds data to the database
how do I get a cycle every 50 iterations connect to the new api, and if he reaches seven then again from the beginning, and so has not yet come to an end user in the database?
Advance thanks!
You could set up an itertools.cycle.
apis = itertools.cycle([api1, api2, api3, api4, api5, api6, api7])
for s,usera in enumerate(all_users):
if (s % 50) == 0:
current_api = apis.next()
name = usera.nickname
name_id = usera.id
print(s)
current_api.request(example)
...
i've searched the forum and found similar questions, but no luck in solving my problem.
My code is designed to swap every two letters of each word using recursion and print the result. For words with an even amount of letters, the word "None" is included in the output and i don't know how to fix...
here's the code:
def encryptLine(line, count):
headline = line[count:]
if length(headline) > 0:
if count == length(line) - 1:
new = headline
return new
elif count <= length(line):
new = head(tail(headline)) + head(headline)
new = new + str(encryptLine(line, count+2))
return new
print(encryptLine('abcd', 0))
the output for 'abcd' is badcNone, which is correct except for the word None. the output for 'abcde' is 'badce', which is correct...
thanks in advance for your help!
Add return "" to the function definition, that is
def encryptLine(line, count):
headline = line[count:]
if length(headline) > 0:
if count == length(line) - 1:
new = headline
return new
elif count <= length(line):
new = head(tail(headline)) + head(headline)
new = new + str(encryptLine(line, count+2))
return new
return ""
Otherwise, the function will return None if length(headline) > 0 does not hold.
None is here because your function return nothing.
There is 1 case where you return nothing it is
if length(headline) <= 0:
In Python, if there is no return to a function and you try to access to a return value, the value will be None.