Istiak Fahim
Istiak Fahim

Reputation: 72

why Search function is not working in django?

After I searched on a specific keyword, Django is not retrieving searched items that matches but it's showing all data. When I search for history it's showing all books though I have history books on the database.

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>  

Upvotes: 0

Views: 383

Answers (1)

Arjun Shahi
Arjun Shahi

Reputation: 7330

You are using the name attribute for search input with searchBook in your template so change in view like this.

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)

Upvotes: 1

Related Questions