我做了一个搜索栏,但是每当我在其中写东西时,链接就会显示http://127.0.0.1:8000/?srh=something
,但我不明白为什么没有显示特定的picture with title
。它向我显示了所有带有标题的图片,但我只想要带有标题的图片,并将其写为搜索栏的标题。在此代码中添加哪些内容?
index.html
{% load static %}
{% static 'images/fulls' as baseUrl %}
{% static 'images/thumbs' as hiUrl %}
<form class="new" method="GET" action="">
<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>
views.py
def index(request):
query = request.GET.get('srh')
if query:
match = 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')
models.py
class Destination(models.Model):
title = models.CharField(max_length=255)
img = models.CharField(max_length=255)
price = models.IntegerField()
答案 0 :(得分:0)
我不明白您为什么使用a和b,但是我认为这可以解决问题
def index(request):
query = request.GET.get('srh')
if query:
match = Destination.objects.get(desc=query)
context = {
'match': match,
}
return render(request, 'index.html', context)
else:
return render(request, 'index.html')
<div>
{ % if match %}
<div>
<a href="{{baseUrl}}/{{match.img}}">
<img src="{{hiUrl}}/{{match.img}}" alt="" />
<h3>{{match.title}}</h3>
</a>
</div>
{% endif %}
</div>