【问题标题】:DJANGO - How to show "Nothing Found for your seach" If no data foundDJANGO - 如果未找到数据,如何显示“未找到您的搜索”
【发布时间】:2021-02-26 23:11:08
【问题描述】:

我想知道当用户搜索不匹配时,是否有办法显示 div,或者至少在 django 中显示“Nothing found”。

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 %} 

但是没有用

非常感谢任何建议/答案!提前致谢!

【问题讨论】:

    标签: django django-views django-templates django-queryset django-filter


    【解决方案1】:

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

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

    {% empty %}{% endfor %} 之间,您可以指定在object_list 中没有元素的情况下要渲染的内容。

    【讨论】:

    • 非常感谢!这是一个很好的解决方案。抱歉,我无法正确查看文档!再次感谢!
    猜你喜欢
    • 1970-01-01
    • 2019-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多