Bhanukiran Bhanukiran - 5 months ago 30
Python Question

How to implement search function in django?

I have many books in a database. Searching the database returns nothing(empty queryset).

In the menu:

<form name="myform" method="POST" action="{% url 'search' %}">
{% csrf_token %}
<input type="text" name="search" placeholder="Search" />
</form>


views.py,

def search(request):
if request.method == 'POST':
book_name = request.POST.getlist('search')
book_name = str(book_name)
try:
status = Add_prod.objects.filter(bookname__icontains=book_name)
#Add_prod class contains a column called 'bookname'
except Add_prod.DoesNotExist:
status = None
return render(request,"search.html",{"books":status})
else:
return render(request,"search.html",{})


My template file,

{% if books %}
<a href="{% url 'buy_book' pk=books.pk %}">
<!--Upon successful search book image with hyperlink appears -->
<img src="{{books.image.url}}" alt="No Image"></a>
<p>{{books.bookname}}</p>
<p>Rs.{{books.price}}</p>
{% endif %}

Answer

There are couple of things I would like to add here..

1) I think search result should be of method GET not POST. You might refer this link to see when to use POST and when to use GET

<form name="myform" method="GET" action="{% url 'search' %}"> 
// see if you need csrf_token here when this is GET request. Your homework

2) views.py

def search(request):        
    if request.method == 'GET': # this will be GET now      
        book_name =  request.GET.get('search') # do some research what it does       
        try:
            status = Add_prod.objects.filter(bookname__icontains=book_name) # filter returns a list so you might consider skip except part
        return render(request,"search.html",{"books":status})
    else:
        return render(request,"search.html",{})

3) django template should be now

{% if books %}
{% for each_book in books %} // books is list here so pick each element using for loop 
    <a href="{% url 'buy_book' pk=each_book.pk %}">
    <!--Upon successful search book image with hyperlink appears -->
    <img src="{{each_book.image.url}}" alt="No Image"></a>
    <p>{{each_book.bookname}}</p>
    <p>Rs.{{each_book.price}}</p>   
{% endfor %}
{% endif %}

This should be working fine.

Also make you sure you have some data in db to fetch you some result on search!