0

I am trying to write the search function where the user submits a wiki search. If the query is in the given list of entries, the user should be redirected to related entry's page. If the query doesn't match the name of an entry but is a substring of any entry, the user should be taken to a page that lists the related entries. My problem is that I couldn't figure out how to logically implement return statements.

The code below works fine:

def search(request):
    sub_list = []
    entries = util.list_entries()
    search = request.GET.get("q")

    for entry in entries:
        if search.lower() == entry.lower():
            return redirect("entry", title= search)
        elif search.lower() in entry.lower():
            sub_list.append(entry)
    return render(request, "encyclopedia/search.html",{
        "title":search,
        "sub_list":sub_list
    })

But when I try to add another condition for the case where the query doesn't match the name of an entry, either it always returns "Not Found":

    for entry in entries:
        if search.lower() == entry.lower():
            return redirect("entry", title= search)
        else:
            if search.lower() in entry.lower():
                sub_list.append(entry)
                return render(request, "encyclopedia/search.html",{
                    "title":search,
                    "sub_list":sub_list
                })
        return HttpResponse("Not Found")

or returns only the first substring match:

    for entry in entries:
        if search.lower() == entry.lower():
            return redirect("entry", title= search)
        else:
            if search.lower() in entry.lower():
                sub_list.append(entry)
                return render(request, "encyclopedia/search.html",{
                    "title":search,
                    "sub_list":sub_list
                })
    return HttpResponse("Not Found")

1 Answer 1

2

I know this is late but if it helps somebody. The issue in your code is indentation. The moment the loop find the first matching substring it renders the page. Left indenting it by two levels should work. Or left indent the "Not found" by one level

1
  • thank you for posting this answer months later. I had been struggling with the issue of my search function exiting the loop before checking all of the entries and your suggestion fixed the bug. Thanks again! Dec 13, 2022 at 5:37

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .