导航栏中的搜索部分无法正常工作 (django)

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

我想在我的导航栏中创建一个搜索框并显示我搜索的食物,但它似乎无法正常工作。我找不到问题出在哪里;我的意思是,如果我搜索一种存在的食物,它什么也没有显示。

我的views.py文件:

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

我的urls.py文件:

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

我的base.html文件:

<form class="form-inline my-2 my-lg-0" action="/search" 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">
                <a class="btn btn-outline-warning" href="{% url 'search_results' %}" type="submit" >Search</a>
              </div>
          </div>
        </form>

您搜索未返回任何查询集的原因是您发布的是查询,而不是获取查询集。这实际上是您错过查询的地方 = 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()

您提交的表单带有 <button type="submit"></button>,因此您应该将表单更改为:

<form class="form-inline my-2 my-lg-0" action="<strong>{% url 'search_results' %}</strong>" 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">
        <<strong>button type="submit"</strong> class="btn btn-outline-warning">Search</button>
      </div>
  </div>
</form>

然后在视图中搜索:

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

    def get_queryset(self):
        query = self.request<strong>.GET</strong>.get('search')  # 🖘 use GET
        if query is not None:
            return Food.objects.filter(name__icontains=query)
        else:
            return <strong>Food.objects.none()</strong>  # 🖘 otherwise still return a queryset