gpt4 book ai didi

python - 如何在django中实现基本搜索?

转载 作者:太空宇宙 更新时间:2023-11-03 16:39:03 24 4
gpt4 key购买 nike

搜索框获取数据但不显示任何结果。这是我到目前为止的代码:

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>

最佳答案

如果我正确理解您的问题,请在不正确的地址上发送请求,更改操作属性:

<form type="get" action="{% url 'your_url_name' %}">

然后表单会将请求发送到正确的地址,而不是在index.html上

关于python - 如何在django中实现基本搜索?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36986303/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com