【问题标题】:How to make search bar working in django?如何使搜索栏在 django 中工作?
【发布时间】:2019-07-14 10:27:10
【问题描述】:

我做了一个搜索栏,我希望它搜索网站中的标题。在键入之前什么都没有出现,但是每当我键入一个标题时,所有标题都会出现。如何解决这个问题?

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

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

【问题讨论】:

  • 有人回答吗?
  • 您正在覆盖 target1 target1 = a, b= [Destination() for __ in range(2)] 。你到底想在那里做什么?
  • 我创建了这个变量target1 以使页面动态化。我没有在index.html 中写标题和图像源,而是写在views.py 中。 Destination() 在 models.py 中。那里是一堂课。
  • 我给出的范围是2,因为target1变量中有两个图像和两个标题

标签: python html django


【解决方案1】:

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

当然,当数据库为空时它不会返回任何对象。

【讨论】:

  • 我没有从数据库中得到任何东西。我只是希望它能够从没有数据库的普通页面中获取标题。我还没有创建数据库。你能帮我解决这个问题吗?
  • 不,创建这样的对象然后过滤/查询它没有任何意义。只需使用数据库 (sqlite)。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2021-05-28
    • 1970-01-01
    • 1970-01-01
    • 2011-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多