簡體   English   中英

為什么當我嘗試搜索產品時,什么也沒有出現?

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

我使用 Django 創建了一個電子商務網站,但當我嘗試搜索產品時搜索結果並未出現。 例如,當我嘗試搜索產品名稱的一部分(如喉嚨噴霧劑)時,即使數據庫中有喉嚨噴霧劑,也沒有任何結果。

我嘗試使用 Post 和 Get 方法,但兩者之間並沒有真正的區別。 我檢查以確保 show_product 頁面的 url 有效並且確實有效。 我期待我所搜索內容的搜索結果。 雖然,搜索頁面通過了,但搜索結果沒有出現。 相反,我得到一個 /search/?searched=throat-spray

我的意見.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})

我的搜索.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>

我的網址.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'),

我的 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>

您正在將名為product的變量傳遞給模板...

return render(request, 'epharmacyweb/search.html', {'searched': searched, 'product': products})

...但是隨后模板嘗試訪問名為products的變量。

{% for product in products %}

您的變量名不匹配。 在視圖中將'product': products更改為'products': products

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM