Home > Net >  Search part in navbar doesn't work properly (django)
Search part in navbar doesn't work properly (django)

Time:01-10

I wanted to create a search box in my navbar and show the food which I search, but it seems it doesn't work properly. I can't find out where's the problem; I mean if I search a food which exists it shows me nothing.

my views.py file:

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

    def get_queryset(self):
        query = self.request.POST.get("search")
        if query is not None:
            return Food.objects.filter(name__icontains=query)
        else:
            return

my urls.py file:

path("search", SearchResultsView.as_view(), name='search_results'),

my base.html file:

<form  action="/search" method="get">
          {% csrf_token %}
          <div >
              <label>
                  <input name="search" type="text"  placeholder="Search Foods ...">
              </label>
              <div >
                <a  href="{% url 'search_results' %}" type="submit" >Search</a>
              </div>
          </div>
        </form>

CodePudding user response:

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

<form  action="{% url 'search_results' %}" method="get">
  {% csrf_token %}
  <div >
      <label>
          <input name="search" type="text"  placeholder="Search Foods ...">
      </label>
      <div >
        <button type="submit" >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')  #            
  •  Tags:  
  • Related