DJANGO / PYTHON 我正在尝试加载http://127.0.0.1:8000/catalog/。如果用户在此页面上输入数据,则表单会将search_query发送到数据库。我的问题是http://127.0.0.1:8000/catalog/无法加载-它导致异常值'search_query'的'MultiValueDictKeyError'异常类型。但是,当用户将数据提交到表单中时(即http://127.0.0.1:8000/catalog/?search_query=biography+of),页面就会加载。我正在尝试使http://127.0.0.1:8000/catalog/加载而用户不必提交搜索查询。
这是我的查看功能:
def index(request):
. . .
num_of_word = []
bookInstance_titles = []
bookInstance_ids = []
num_of_word = BookInstance.objects.filter(status='a', book__title__contains=request.GET['search_query']).count()
bookInstances = BookInstance.objects.filter(status='a', book__title__contains=request.GET['search_query'])
for i in bookInstances:
bookInstance_titles.append(str(i.book))
bookInstance_ids.append(str(i.id))
context = {
. . .
'num_of_word': num_of_word,
'bookInstance_titles': bookInstance_titles,
'bookInstance_ids': bookInstance_ids,
}
我认为问题在于变量(num_of_word和bookInstances)正在尝试访问请求的search_query,但是/ catalog /请求没有搜索查询。经过研究,我仍然不确定如何解决这个问题。
谢谢!
答案 0 :(得分:1)
您尝试访问不存在的GET查询。您必须检查request.GET中是否存在search_query或仅对其使用.get函数。见下文:
def index(request):
. . .
num_of_word = []
bookInstance_titles = []
bookInstance_ids = []
num_of_word = BookInstance.objects.filter(status='a', book__title__contains=request.GET.get('search_query', '').count()
bookInstances = BookInstance.objects.filter(status='a', book__title__contains=request.GET.get('search_query', ''))
for i in bookInstances:
bookInstance_titles.append(str(i.book))
bookInstance_ids.append(str(i.id))
context = {
. . .
'num_of_word': num_of_word,
'bookInstance_titles': bookInstance_titles,
'bookInstance_ids': bookInstance_ids,
}
答案 1 :(得分:1)
希望它会起作用。根据您的代码使用以下内容。
if request.method == 'GET' and 'q' in request.GET: #q is search Input field reference
num_of_word = []
bookInstance_titles = []
bookInstance_ids = []
num_of_word = BookInstance.objects.filter(status='a', book__title__contains=request.GET.get('search_query', '').count()
bookInstances = BookInstance.objects.filter(status='a', book__title__contains=request.GET.get('search_query', ''))
for i in bookInstances:
bookInstance_titles.append(str(i.book))
bookInstance_ids.append(str(i.id))
context = {
. . .
'num_of_word': num_of_word,
'bookInstance_titles': bookInstance_titles,
'bookInstance_ids': bookInstance_ids,
}
else{
context = {
. . .
'num_of_word': "", #What you want to pass
'bookInstance_titles': "", #What you want to pass
'bookInstance_ids': "", #What you want to pass
}
}