Python 如何使搜索栏在django中工作?
我做了一个搜索栏,我想它搜索的标题,这是在网站上。在键入之前,不会显示任何内容,但每当我键入一个标题时,所有标题都会显示。如何解决这个问题 index.html views.pyPython 如何使搜索栏在django中工作?,python,html,django,Python,Html,Django,我做了一个搜索栏,我想它搜索的标题,这是在网站上。在键入之前,不会显示任何内容,但每当我键入一个标题时,所有标题都会显示。如何解决这个问题 index.html views.py {%csrf_令牌%} 搜寻 {target1%中dest1的%1} {dest1%时为%1} {%endif%} {%endfor%} .py代码: def paylasimlar(request): keyword = request.GET.get("keyword") if
{%csrf_令牌%}
搜寻
{target1%中dest1的%1}
{dest1%时为%1}
{%endif%}
{%endfor%}
.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" >
{%csrf_令牌%}
搜索
对象。过滤器从数据库中读取,但数据库中没有对象
这就足够了:
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')
但是,当数据库为空时,它当然不会返回任何对象。有人回答吗?您正在覆盖范围(2)内的_u的target1target1=a,b=[Destination()。你到底想在那里做什么?我创建了这个变量target1
,以使页面动态。我没有在index.html
中编写标题和图像源代码,而是在views.py
中编写<代码>目标()
位于models.py中。这是一个类。我给出的范围是2,因为target1
variable中有两个图像和两个标题。我没有从数据库中得到任何信息。我只是希望它能够从没有数据库的普通页面获取标题。我还没有创建数据库。你能帮我吗?不,创建这样的对象然后过滤/查询是没有任何意义的。只需使用数据库(sqlite)。
<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" >
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')