I'm trying to take the input from a form in Django and to then search storage and display any matches here is the code I have so far.
views.py
def search(request):
input = request.GET.get('q')
return render(request, "encyclopedia/search.html", {
"entry": util.get_entry(input) == None,
"display": util.get_entry(input)
})
search.html
{% extends "encyclopedia/layout.html" %}
{% block title %}
{% endblock %}
{% block body %}
{% if entry %}
<div>No entry found</div>
{% else %}
<div>{{ display }}</div>
{% endif %}
{% endblock %}
layout.html
<div class="row">
<div class="sidebar col-lg-2 col-md-3">
<h2>Wiki</h2>
<form action="{% url 'search' %}" method="get">
<input class="search" type="text" name="q" placeholder="Search Encyclopedia">
<input type="submit">
</form>
<div>
<a href="{% url 'index' %}">Home</a>
</div>
<div>
urls.py
urlpatterns = [
path("", views.index, name="index"),
path("<str:name>", views.entry, name="entry"),
path("search", views.search, name="search")
]
utils.py
def get_entry(title):
"""
Retrieves an encyclopedia entry by its title. If no such
entry exists, the function returns None.
"""
try:
f = default_storage.open(f"entries/{title}.md")
return f.read().decode("utf-8")
except FileNotFoundError:
return None
It works with taking you to the search page but always displays no entry found even if the entry does exist.
This is my first project using Django so its pretty new, I'm assuming there is an issue with how I'm feeding in the form input to the util.get_entry() function.
After reading the documentation for forms in Django I still cant seem to find any reference about how to get this working. any help would be much appreciated.
After some further digging i've found that the line in views.py
input = request.GET.get('q')
is assigning the variable the value of 'search' each time instead of the user form input.