如何让搜索栏在Django工作?

2024-10-02 10:20:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我做了一个搜索栏,我想它搜索的标题,这是在网站上。在键入之前,什么都不显示,但每当我键入一个标题时,所有标题都会出现。如何解决这个问题?你知道吗

索引.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')

视图.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>

Tags: div标题imggetindex键入iftitle
2条回答

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')

但当数据库为空时,它当然不会返回任何对象。你知道吗

.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" >

相关问题 更多 >

    热门问题