搜索框获取数据但不显示任何结果。 到目前为止,这是我的代码:
views.py
def search(request):
if 'q' in request.GET and request.GET['q']:
q = request.GET['q']
books = Advent.objects.filter(title__icontains=q)
return render(request, 'search_results.html', {'books': books, 'query': q})
else:
return HttpResponse('Please submit a search term.')
urls.py
url(r'^your_url/?$', 'myblog.views.search', name='your_url_name'),
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 %}
的index.html
<form type="get" action=".">
<input type="search" id="q" name="q" placeholder="Search..."/>
</form>
答案 0 :(得分:1)
如果我正确理解您的问题,请在不正确的地址上发送请求,更改操作属性:
<form type="get" action="{% url 'your_url_name' %}">
然后表单会将请求发送到正确的地址而不是index.html
答案 1 :(得分:0)
我会做这样的事情:
<强> views.py:强>
from django.views.decorators.http import require_http_methods
@require_http_methods(['GET'])
def search(request):
q = request.GET.get('q')
if q:
books = Advent.objects.filter(title__icontains=q)
return render(request, 'search_results.html', {'books': books, 'query': q})
return HttpResponse('Please submit a search term.')
<强>的index.html:强>
<form type="get" action="{% url 'your_url_name' %}" accept-charset="utf-8">
<input type="search" id="q" name="q" placeholder="Search..."/>
</form>
视图需要GET方法。您也不需要else
语句,您可以将查询移到if
语句之外。这会稍微缩短你的代码。
在您的HTML中,您需要将操作请求更改为正确的网址。如果您没有在表单和视图之间映射写入URL,则在提交表单时它将不知道该怎么做。