我创建了一个搜索栏,但每当我在其中写入内容时,链接都会显示 http://127.0.0.1:8000/?srh=something
并且我不明白为什么具体 带标题的图片
未显示。它向我显示了所有带有标题的图片,但我只想要带有标题的图片,我在搜索栏中写为标题。这段代码中需要添加哪些内容?
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()
最佳答案
我不明白你为什么使用 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>
关于python - 每当我在 django 的搜索栏中输入内容时,如何使 require 对象可用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57024837/