首页 > 解决方案 > django 中产品搜索的上下文

问题描述

我想按类别在我的应用中搜索产品,从 firebase 数据库中检索数据。搜索有效,但不显示产品,我不知道要传递什么其他上下文。我是 Django 的新手,所以任何帮助都将不胜感激。

这是我的 Welcome.html:

<form class="form-inline my-2 my-lg-0" method="get" action="/postsign" id="s">
  {% csrf_token %}
  <input class="form-control mr-sm-2" type="search" value="{{ category }}" placeholder="Search by category" aria-label="Search" name="Search">
  <button class="btn btn-outline-success my-2 my-sm-0" type="submit" onclick="location.href='/postsign/?category={{ category }}'" form="s">Search</button>
</form>
</div>
</nav>




 <div class="container">

      <div class="col-md-4">

          <div class="cards">
            {% for product in category %}


             <div class="card" style="width: 18rem;">


                 <img class="card-img-top" src="{{ product.image }}" alt="Card image cap">
                 <div class="card-body">
                     <h5 class="card-title">{{ product.pname }}</h5>
                     <p class="price">{{ product.price }}</p>
                     <p class="card-text">{{ product.description }}</p>
                     <button class="btn btn-primary cart">Add to cart</button>
                     <button class="btn btn-primary" onclick="location.href='{% url 'productView' %}'">View product</button>
                 </div>

             </div>


            {% endfor %}
          </div>
          </div>

      </div>  

以下是观点:

def postsign(request):
 if request.method == 'GET' and 'csrfmiddlewaretoken' in request.GET:

   search = request.GET.get('Search')
   search = search.lower()
   timestamps = database.child("Products").shallow().get().val()



   pcategory = []
   for i in timestamps:
       category = database.child("Products").child(i).child("category").get().val()
       category = str(category)+"$"+str(i)
       pcategory.append(category)
   matching =[str(string) for string in pcategory if search in string.lower()]


   s_category = []
   s_id = [] 

   for i in matching:
      category,ids=i.split("$")
      s_category.append(category)
      s_id.append(ids)
   data = services.get_products()
   return render(request, "Welcome.html",{'category':s_category})

这是我的数据库的外观:

products{
  timestamp{
    name:...
    category:...
    }
  timestamp{
   name:..
   category:...

...

标签: pythondjangopython-3.xfirebase-realtime-database

解决方案


推荐阅读