gpt4 book ai didi

python - django中如何实现搜索功能?

转载 作者:行者123 更新时间:2023-12-02 19:42:07 37 4
gpt4 key购买 nike

我的数据库中有很多书。搜索数据库不会返回任何内容(空查询集)。

在菜单中:

<form name="myform" method="POST" action="{% url 'search' %}">  
{% csrf_token %}
<input type="text" name="search" placeholder="Search" />
</form>

views.py,

def search(request):        
if request.method == 'POST':
book_name = request.POST.getlist('search')
try:
status = Add_prod.objects.filter(bookname__icontains=book_name)
#Add_prod class contains a column called 'bookname'
except Add_prod.DoesNotExist:
status = None
return render(request,"search.html",{"books":status})
else:
return render(request,"search.html",{})

我的模板文件,

{% if books %}
<a href="{% url 'buy_book' pk=books.pk %}">
<!--Upon successful search book image with hyperlink appears -->
<img src="{{books.image.url}}" alt="No Image"></a>
<p>{{books.bookname}}</p>
<p>Rs.{{books.price}}</p>
{% endif %}

最佳答案

我想在这里补充几件事..

1)我认为搜索结果应该是GET方法而不是POST方法。您可以引用this查看何时使用 POST 以及何时使用 GET 的链接

<form name="myform" method="GET" action="{% url 'search' %}"> 
// see if you need csrf_token here when this is GET request. Your homework

2)views.py

def search(request):        
if request.method == 'GET': # this will be GET now
book_name = request.GET.get('search') # do some research what it does
try:
status = Add_prod.objects.filter(bookname__icontains=book_name) # filter returns a list so you might consider skip except part
return render(request,"search.html",{"books":status})
else:
return render(request,"search.html",{})

3) django 模板现在应该是

{% if books %}
{% for each_book in books %} // books is list here so pick each element using for loop
<a href="{% url 'buy_book' pk=each_book.pk %}">
<!--Upon successful search book image with hyperlink appears -->
<img src="{{each_book.image.url}}" alt="No Image"></a>
<p>{{each_book.bookname}}</p>
<p>Rs.{{each_book.price}}</p>
{% endfor %}
{% endif %}

这应该可以正常工作。

还要确保数据库中有一些数据,以便在搜索时获取一些结果!

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

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