Reputation: 2646
I am working on my first django project and I encountered a problem that I could not find any viable solution. So, I am trying to create an e-commerce website. I created a basic search bar and I am trying to render everything that matches the input. The problem occurred at one of the edge cases. If I send an empty input, the following error is being raised:
Exception Value:
The view mainpages.views.search didn't return an HttpResponse object. It returned None instead.
I tried to handle this, but I failed. I've searched for answers, but unsuccessfully. I sincerely appreciate your time!
Code: views.py
def search(request):
if request.method == 'GET' and 'q' in request.GET:
query = request.GET.get('q')
try:
if query:
objects_list= ComputerScienceProducts.objects.filter(
Q(name__icontains=query)
)
if list(objects_list) is None:
return render(request, 'search_error.html')
else:
return render(request, 'search_result.html', {"objects_list": objects_list})
except:
return render(request, 'search_error.html')
else:
return render(request, 'search_error.html')
template:
{% block cont2 %}
<div class="background"></div>
<div class="inp">
<form action="{% url 'search_results' %}" method="get">
{% csrf_token %}
<label>
<i class="bi bi-search" style="position: absolute; margin-left: 15px;margin-top: 13px;"></i>
<input type="text" placeholder="What are you looking for?" class="search" name="q">
</label>
</form>
</div>
<div class="container" style="margin-top: 20px;">
{% endblock %}
{% block content %}
{% if objects_list %}
{% for prod in objects_list %}
<div class="card" id="cardDisplay">
<img class="card-img-top" src="{{ prod.img.url }}" alt="Card image" id="image_prod">
<div class="card-body">
<h4 class="card-title"> {{ prod.name }}</h4>
<p class="card-text">Price: {{ prod.price }} lei <br>
<a href="{% url 'prod_details' prod.pk %}" class="card-text">Details</a></p>
<button type="submit" class="btn btn-primary">Add to chart</button>
</div>
</div>
{% endfor%}
{% else %}
<p class="updt"> No item has been matched to your search</p>
{% endif %}
</div>
{% endblock %}
Upvotes: 1
Views: 1096
Reputation: 2235
This return all items...
def search(request):
if request.method == 'GET' and 'q' in request.GET:
query = request.GET.get('q')
if query is None:
query = ""
.....
This return error page..
def search(request):
if request.method == 'GET' and 'q' in request.GET:
query = request.GET.get('q')
try:
if query:
objects_list= ComputerScienceProducts.objects.filter(
Q(name__icontains=query)
)
if list(objects_list) is None:
return render(request, 'search_error.html')
else:
return render(request, 'search_result.html', {"objects_list": objects_list})
➡➡else:
➡➡return render(request, 'search_error.html')
except:
return render(request, 'search_error.html')
else:
return render(request, 'search_error.html')
Upvotes: 2