[Answered ]-Search part in navbar doesn't work properly (django)

1๐Ÿ‘

โœ…

You submit the form with a <button type="submit"></button>, so you should change the form to:

<form class="form-inline my-2 my-lg-0" action="{% url 'search_results' %}" method="get">
  {% csrf_token %}
  <div class="input-group">
      <label>
          <input name="search" type="text" class="form-control" placeholder="Search Foods ...">
      </label>
      <div class="input-group-append">
        <button type="submit" class="btn btn-outline-warning">Search</button>
      </div>
  </div>
</form>

In the view we then search with:

class SearchResultsView(ListView):
    model = Food
    template_name = 'restaurant/food_search_results.html'
    context_object_name = 'data'

    def get_queryset(self):
        query = self.request.GET.get('search')  # ๐Ÿ–˜ use GET
        if query is not None:
            return Food.objects.filter(name__icontains=query)
        else:
            return Food.objects.none()  # ๐Ÿ–˜ otherwise still return a queryset

0๐Ÿ‘

The reason why you search is not returning any queryset is because you are posting the query, instead of getting the querySet. This is acutually where you missed the query = self.request.POST.get("search"), Instend of query = self.request.GET.get("search")


class SearchResultsView(ListView):
    model = Food
    template_name = "restaurant/food_search_results.html"
    context_object_name = "data"

    def get_queryset(self):
        query = self.request.GET.get("search")
        if query is not None:
            return Food.objects.filter(name__icontains=query)
        else:
            return Food.objects.none()
๐Ÿ‘คGodda

Leave a comment