简体   繁体   English

如何使搜索栏在 Django 中工作?

[英]How to make search bar working in django?

I made a search bar and I want it to search the titles which is in the site.我做了一个搜索栏,我希望它搜索网站中的标题。 Before typing nothing appears but whenever I type one title all the titles appear.在输入任何内容之前,但每当我输入一个标题时,所有标题都会出现。 How to resolve this issue?如何解决这个问题?

index.html索引.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视图.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>

objects.filter reads from the database, but you have no objects in the database. objects.filter从数据库读取,但数据库中没有对象。

This should be enough:这应该足够了:

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

But of course it will not return any objects when the database is empty.但是当然当数据库为空时它不会返回任何对象。

.py codes: .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})

and .html和.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" >

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM