我不确定为什么这会发生在我的两个搜索函数之间。
下面是我的第一个搜索函数
def search(request):
if 'q' in request.GET and request.GET['q']:
q = request.GET['q']
books = Book.objects.filter(title__icontains = q)
return render_to_response('search_results.html', {'books': books, 'query': q})
else:
return render_to_response('search_form.html', {'error': True})使用此函数,当我进入
http://127.0.0.1:8000/search/ 在我的浏览器中,显示的是我创建的搜索栏和消息。此外,当我按下搜索按钮时,链接将自动更新为
http://127.0.0.1:8000/search/?q=然而,对于我的搜索功能的第二个版本
def search(request):
error = False
if 'q' in request.GET['q']:
q = request.GET['q']
if not q:
error = True
else:
books = Book.objects.filter(title__icontains = q)
return render_to_response('search_results.html', {'books': books, 'query': q})
return render_to_response('search_form.html',{'error':error})如果我进入
http://127.0.0.1:8000/search/ 在我的浏览器里,我会得到
Exception Type: MultiValueDictKeyError
Exception Value: "Key 'q' not found in <QueryDict: {}>"如果我在浏览器中手动创建链接
http://127.0.0.1:8000/search/?q= 错误消息将消失,但如果我执行搜索,我得到的只是一个搜索栏,它除了更新指向我在搜索栏中输入的任何内容的链接并运行搜索之外,什么也不做。
EX: searched for eggs --> http://127.0.0.1:8000/search/?q=eggs以下是我的HTML文件
search_results.html
<p>You searched for: <strong>{{ query }}</strong></p>
{% if books %}
<p>Found {{ books|length }} book{{ books|pluralize }}.</p>
<ul>
{% for book in books %}
<li>{{ book.title }}</li>
{% endfor %}
</ul>
{% else %}
<p>No books matched your search criteria.</p>
{% endif %}search_form.html
<html>
<head>
<title>Search</title>
</head>
<body>
{% if error %}
<p style = "color: red;">Please submit a search term.</P>
{% endif %}
<form action = "/search/" method = "get">
<input type = "text" name = "q">
<input type = "submit" value = "Search">
</form>
</body>
</html>任何帮助都是非常感谢的!谢谢!
发布于 2013-02-25 19:53:30
您可以键入:
if 'q' in request.GET['q']:并且您应该键入:
if 'q' in request.GET:它失败是因为您试图访问缺少的项。
您还可以执行以下操作:
if request.GET.get('q', False):发布于 2013-02-25 20:06:25
为了补充祖鲁所说的,你可以使用属于字典的get()方法来整理一下代码:
def search(request):
query = request.GET.get("q", None)
if query:
books = Book.objects.filter(title__icontains = query)
return render_to_response("search_results.html", {"books": books, "query": query})
# if we're here, it's because `query` is None
return render_to_response("search_form.html", {"error": True})https://stackoverflow.com/questions/15066253
复制相似问题