我做了一个搜索栏,我希望它搜索站点中的标题。在键入任何内容之前,什么都没有出现,但是只要我键入一个标题,所有标题都会出现。如何解决这个问题?
index.html
def index(request):
query = request.GET.get('srh')
if query:
target1 = Destination.objects.filter(title__icontains=query)
target1 = a, b= [Destination() for __ in range(2)]
a.img = 'Article.jpg'
b.img = 'Micro Tasks.jpeg'
a.title = 'Article Writing'
b.title = 'Micro Tasks'
context = {'target1': target1}
return render(request, 'index.html', context)
else:
return render(request, 'index.html')
views.py
<form class="love" method="GET" action="">
{% csrf_token %}
<input type="text" placeholder='Search..' name="srh" value="{{request.GET.srh}}"> <br>
<button type="submit" class="btn btn-danger"> Search </button>
</form>
<div>
{% for dest1 in target1 %}
{% if dest1 %}
<div>
<a href="{{baseUrl}}/{{dest1.img}}">
<img src="{{hiUrl}}/{{dest1.img}}" alt="" />
<h3>{{dest1.title}}</h3>
</a>
</div>
{% endif %}
{%endfor%}
</div>
答案 0 :(得分:0)
objects.filter
从数据库读取,但是数据库中没有对象。
这应该足够了:
def index(request):
query = request.GET.get('srh')
if query:
destinations = Destination.objects.filter(title__icontains=query)
context = {'target1': destinations}
return render(request, 'index.html', context)
else:
return render(request, 'index.html')
但是,当数据库为空时,它当然不会返回任何对象。
答案 1 :(得分:-1)
.py代码:
def paylasimlar(request):
keyword = request.GET.get("keyword")
if keyword:
paylasimlar = Makale.objects.filter(Q(baslik__contains=keyword) | Q(icerik__contains=keyword))
return render(request, "feed.html", {"paylasimlar": paylasimlar})
和.html
<form style="text-align: right">
{% csrf_token %}
<button type="submit" class="btn btn-default" style="float: right">
<i class="material-icons">search</i>
</button>
<input type="text" name="keyword" class="form-control" placeholder="Anı Ara..." style="border-radius: 20px;float: right;width: 20%" aria-label="Search" >