【问题标题】:why Search function is not working in django?为什么搜索功能在 django 中不起作用?
【发布时间】:2021-07-19 11:22:08
【问题描述】:

在我搜索特定关键字后,Django 不会检索匹配的搜索项,但它会显示所有数据。当我搜索 history 时,它会显示所有书籍,尽管我的数据库中有历史书籍。

views.py

def home(request):
    if request.method == 'POST':
        searchName = request.POST.get('Search')
        if not searchName :
             searchName = ""
        
        context={
            'data': Book.objects.filter(bookname__contains=searchName)
        }
        return render(request, 'library_site/home.html',context)
    else:
        context={
            'data': Book.objects.all()
        }           
    return render(request, 'library_site/home.html',context)

form field in html

<form method="POST" action="{% url 'home' %}">
    {% csrf_token %}
    <input   class="search-input" type="text"  name="searchBook" placeholder="Search Book Name here...">
    <input   class="btn" type="submit"  name="search" value="Search">                
</form>  

【问题讨论】:

  • 因为您的姓名属性“搜索”与“搜索”不匹配

标签: django django-models django-views django-templates django-urls


【解决方案1】:

您正在使用 name 属性 在模板中使用 searchBook 进行搜索输入,因此请像这样更改视图。

if request.method == 'POST':
    searchName = request.POST.get('searchBook', '')
        
    context={
       'data': Book.objects.filter(bookname__contains=searchName)
        }
    return render(request, 'library_site/home.html',context)

【讨论】:

  • 谢谢。我怎么能错过这个!!!!-_-。我很后悔自己...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-25
  • 1970-01-01
  • 2021-06-29
  • 2015-02-27
  • 2012-06-28
  • 1970-01-01
相关资源
最近更新 更多