Why when I try to search for a product, nothing comes up?

Question:

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 class="col">
    <div class="card shadow-sm">
      <img class="img-fluid" alt="Responsive image" src="{{ product.image.url }}">
      <div class="card-body">
        <p class="card-text">
          <a class="text-dark text-decoration-none" href="{{ product.get_absolute_url }}">{{ product.title }}</a>
        </p>
        <div class="d-flex justify-content-between align-items-center">
          <small class="text-muted"></small>
        </div>
      </div>
    </div>
  </div>
Asked By: cantony2

||

Answers:

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.

Answered By: John Gordon
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.