Home > Blockchain >  Django Search functionality: form returns None
Django Search functionality: form returns None

Time:10-21

i am trying to build a django search functionality for my app but the input form keeps returning a none

views.py

def search(request):
   if request.method == 'POST':
      query = request.POST.get('text')
      houses = Product.objects.filter(name__contains='query')
      context = {
         'houses':houses,
      }
   return render (request, 'searchresult.html', context)

search.html

<form>
   <input type='text' placeholder='search houses>
   <button type='submit'>Search</button>
</form>

CodePudding user response:

First off, your python indentation is invalid, and your HTML is also invalid on the input line. I will assume this is a typo in the question, but if not, you have issues there.

Your main problem is the filter for houses:

houses = Product.objects.filter(name__contains='query')

is looking for a name containing the string "query". You need the variable you've just defined.

houses = Product.objects.filter(name__contains=query)

CodePudding user response:

  1. You have an indentation issue in the code you have posted.

  2. You need to add action and method in your Form.

     <form action="/url_of_search/" method="post">
    
  3. Missing quote in input line.

     <input type='text' placeholder='search houses'>
    
  4. You need to use query instead of 'query' in the filter.

    Product.objects.filter(name__contains=query)
    

CodePudding user response:

Things missing in html code:

  1. form action attribute
  2. form method attribute
  3. input field name attribute
<!-- add form attributes method and action -->
<form method="POST" action="{% url '<url_name>' %}">
   <!-- add input attribute name to identify the field and pass the value in request body -->
   <input type='text' placeholder='search houses' name='search_text'>
   <button type='submit'>Search</button>
</form>

update views for search

def search(request):
   if request.method == 'POST':
      # use input field name to get the search text
      query = request.POST.get('search_text')
      houses = Product.objects.filter(name__contains=query)
      context = {
         'houses':houses,
      }
   return render (request, 'searchresult.html', context)
  • Related