I have a search bar on the side of the webpages of the app I'm working on, what I'm trying to do is have my search view take in the user's query, compare it with a list of entries and if what the user typed in matches the title of any of the entries available, search should redirect to another view called title which handles rendering the HTML file of the entry the user searched for along with matching it with the appropriate URL (i.e if the user searches for the Django entry, title renders HTML file of said entry and assigns it the URL "example.com/Django")
The problem lies in the fact that every time i redirect from search to title, title renders the HTML file reserved for the case in which no entry matches what the user searched for, no matter whether the entry is available or not.
It should also be noted that the path for the search view is a mess. if i write the path like that path("<str:search>", views.search, name="search") i get a NoReverseMatch error saying that Django was expecting an argument but received none, but path("search", views.search, name=search) causes the rendered error page to have the URL "example.com/search" which is not what i want, i want it to redirect to title so that the title view assigns the correct URL.
i am new to Django so my apologies for the long question, but I've been cracking at this problem for days with no use, Below is the code for both title and search views, urls.py and the HTML code of the search bar (the form). Please do ask for more info should you need it.
Thank you in advance for your help.
HTML
<form action="{% url 'wiki:search' %}" method="POST">
{% csrf_token %}
<input class="search" type="text" name="q" placeholder="Search Encyclopedia">
</form>
views.py
def title(request, title):
entry = util.get_entry(title)
if entry == None:
return render(request, "encyclopedia/error.html")
else:
return render(request, "encyclopedia/entry.html", {
"entry": entry,
})
def search(request):
if request.method == "POST":
query = request.POST["q"]
entries = util.list_entries
if query in entries:
if util.get_entry(query) == None:
return render(request, "encyclopedia/error.html")
else:
return redirect('wiki:title', title=query)
else:
return render(request, "encyclopedia/index.html")
urls.py
app_name = "wiki"
urlpatterns = [
path("", views.index, name="index"),
path("<str:title>", views.title, name="title"),
path("search", views.search, name="search")
]