DJANGO - 如何显示 "Nothing Found for your seach" 如果没有找到数据

DJANGO - How to show "Nothing Found for your seach" If no data found

我想知道是否有办法在用户搜索没有匹配项时显示 div,或者至少在 django 中显示“未找到”。

views.py

class TaskSearchView(LoginRequiredMixin, ListView):
    template_name = 'task_app/task_search.html'
    model = Task

    def get_queryset(self):
        query = self.request.GET.get('q')
        usr = self.request.user
        if query:
            object_list = self.model.objects.filter(Q(title__icontains=query) & Q(is_public = True) | 
            Q(title__icontains=query) & Q(author = usr) | Q(title__icontains=query) & Q(responsable = usr)) 
           
        else:
            object_list = self.model.objects.none()
        return object_list

task_search.html

 <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
        <h6 class="m-0 font-weight-bold text-primary">Seach Results for: {{ request.GET.q }}</h6>
      </div>
....
 {% for query in object_list %}
      </thead>
        <tbody>
      <tr>
          {% if query.importance == "H" %}
          <th  scope="row" data-toggle="tooltip" data-placement="top" title="HIGH"><i style="color: red" class="fas fa-bookmark"></i></th>
          {% endif %}
          {% if query.importance == "M" %}
          <th scope="row" data-toggle="tooltip" data-placement="top" title="Medium"><i style="color: orange" class="fas fa-bookmark"></i></th>
          {% endif %}
.....
      </tr>
      {% endfor %}

如果查询为空或没有结果,我会得到:

但是我想显示一个新表格,或者一条消息“找不到任何东西..”,这可能吗?我试过:


{% if object_list != None %}
show results
{%else%}
show not found, form, div...
{% endif %} 

但是没用

非常感谢advice/answer!提前致谢!

您可以使用 {% for … %} … {% empty %} … {% endfor %} template block [Django-doc]:

<table>
<thead>
    …
</thead>
<tbody>
  {% for query in object_list %}
    <tr>
      …
    </tr>
  {% <b>empty</b> %}
    <tr><td colspan="6">Nothing found</td></tr>
  {% endfor %}
</tbody>
</table>

{% empty %}{% endfor %} 之间,您可以指定在 object_list.

中没有元素时要渲染的内容