I would like to know if there is a way to show a div, or at least "Nothing found" in django when there is no match for the user search.
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 the query is empty or there is no result I get this:
but I would like to show a new form, or a message "nothing found..", is that possible? I tried with:
{% if object_list != None %}
show results
{%else%}
show not found, form, div...
{% endif %}
But it didn't work
Any advice/answer is much appreciated! Thanks in advance!
You can work with a {% 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>
Between the {% empty %}
and the {% endfor %}
, you thus specify what to render in case there are no elements in object_list
.