I've created an ecommerce website using Django, though the search results aren't coming up when I try to search for a product. For example, when I try to search for part of a product title, like throat spray, nothing comes up even though there is a throat spray in the database.
I tried using the Post and Get methods though it didn't really make any difference between the two. I checked to make sure the url for the show_product page works and it does. I'm expecting search results for what I searched for. Though, the search page goes through, nothing comes up as the search results. Instead I get a /search/?searched=throat-spray
My views.py:
def search(request):
if 'searched' in request.GET:
searched = request.GET['searched']
products = Product.objects.filter(title__icontains=searched)
return render(request, 'epharmacyweb/search.html', {'searched': searched, 'product': products})
My search.html:
<center>
{% if searched %}
<h1>Search Results for {{ searched }}</h1>
<br>
{% for product in products %}
<a href="{% url 'epharmacyweb/show-product' product.title %}">{{ product }}</a>
{% endfor %}
</br>
{% else %}
<h1>You haven't searched anything yet...</h1>
{% endif %}
</center>
My urls.py:
path('search/', views.search, name='search'),
path('search-error/', views.search_error, name='search_error'),
path('show-product/', views.show_product, name='show-product'),
My show_product.html:
<div >
<div >
<img alt="Responsive image" src="{{ product.image.url }}">
<div >
<p >
<a href="{{ product.get_absolute_url }}">{{ product.title }}</a>
</p>
<div >
<small ></small>
</div>
</div>
</div>
</div>
CodePudding user response:
You're passing a variable named product
to the template...
return render(request, 'epharmacyweb/search.html', {'searched': searched, 'product': products})
... but then the template tries to access a variable named products
.
{% for product in products %}
You have a variable name mismatch. Change 'product': products
to 'products': products
in the view.