Trouble rendering results from searchbar in Django

Viewed 55

I have been working on a search bar in django and I am close but having some issues rendering the results to the page.

Views.py

class SearchResultsView(ListView):
    model = Project
    template_name = 'search_results.html'
    
    def get_queryset(self):
        proj=self.request.GET.get('proj')
        proj_list=Project.objects.filter(
            Q(name__icontains=proj) | Q(projectTag__icontains=proj)
        )
        proj_list1=Project.objects.filter(
            Q(department__icontains=proj)
        )
        proj_list2 = list(set(proj_list) & set(proj_list1))
        return proj_list2

class SearchPageView(TemplateView):
    template_name = 'searchbar.html'

search_results.html

{% extends 'main/base.html' %}
<html>

{%block content%}
<h1> Search Results </h1>

{% if proj %}
<ul>
    {% for project in proj_list2%}
     <li>
        {{project.name}}, {{project.department}}, {{project.projectTag}}
     </li>
    {% endfor %}
</ul>
{% else %}
<h2>sorry, no results</h2>
{% endif %}
{%endblock%}
</html>

Whenever I search something that should definitely yield results, I get "sorry, no results."

Thank you. Please help me to understand my disconnect. The bigger aim for this is to then add different models to query from (i.e. not just search in projects, but also search by user).

1 Answers

You are checking the wrong variable. The collection of elements is object_list, not proj or proj_list2:

{% if object_list %}
<ul>
    {% for project in object_list %}
     <li>
        {{project.name}}, {{project.department}}, {{project.projectTag}}
     </li>
    {% endfor %}
</ul>
{% else %}
    <h2>sorry, no results</h2>
{% endif %}

The search is also quite odd, you only retrieve items if both the department and the name or the tag matches. We can simplify this to:

class SearchResultsView(ListView):
    model = Project
    template_name = 'search_results.html'
    
    def get_queryset(self):
        proj = self.request.GET.get('proj')
        return =Project.objects.filter(
            Q(name__icontains=proj) | Q(projectTag__icontains=proj),
            department__icontains=proj
        )

but it is odd that the department and the name for example should match. If you want to match any of the three, we can work with:

class SearchResultsView(ListView):
    model = Project
    template_name = 'search_results.html'
    
    def get_queryset(self):
        proj = self.request.GET.get('proj')
        return =Project.objects.filter(
            Q(name__icontains=proj) |
            Q(projectTag__icontains=proj) |
            Q(department__icontains=proj)
        )
Related