2016-03-02 77 views
1

我想在我的django網站上做一個搜索表單。 所以,我只是創造一個產品搜索列表:Django搜索html表格

class ProductSearchListView(ProductList): 
    """ 
    Display a Product List page filtered by the search query 
    """ 
    paginate_by = 10 

    def get_queryset(self): 
     result = super(ProductSearchListView, self).get_queryset() 

     query = self.request.GET.get('q') 

     if query: 
      query_list = query.split() 
      result = result.filter(
       reduce(
        operator.and_, 
        (Q(nome__icontains=q) for q in query_list) 
       ) | 
       reduce(
        operator.and_, 
        (Q(categoria__icontains=q) for q in query_list) 
       ) 
      ) 

     return result 

在我的HTML我想有一個框,使一個簡單的搜索,並點擊回車鍵,用戶應該看到的所有產品的列表。

<form id="searchform" action="{% do something %}" method="get" accept-charset="utf-8"> 
    <input .../> 
</form> 

{% if list_of_products_returned_from_search == null %} 
    <div ...> 
     None product found. 
    </div> 
{% elif products exists %} 
    {% for product in products %} 
     Name: {{product.name}} 
    {% endfor %} 
{% endif %} 
+0

那麼問題是什麼? ' karthikr

+0

問題是「如何在html中調用query_set」方法? – dsbonafe

+0

@ user2732966取決於它在上下文中的保存方式。 ProductList中有什麼? – zanderle

回答

0

我解決了這個問題。

首先,我在views.py創建一個函數:

def return_home(request): 
    lista_de_produtos = Produto.objects.all() 
    query = request.GET.get("q") 
    if query: 
     query_list = query.split() 
     lista_de_produtos = lista_de_produtos.filter(nome__icontains=query) 


    context = { 
     "produtos": lista_de_produtos, 
    } 
    return render(request, 'homepage.html', context) 

後,我寫的HTML代碼:

     {% if produtos %} 
          <ul id="flexiselDemo3"> 
         {% for produto in produtos %} 
           <li> 
            <div class="col-md-3 biseller-column"> 
             <a href="single.html"> 
              <img src="{{produto.foto}}"/> 
              <span class="price">R&#36; {{produto.preco}}</span> 
             </a> 
             <div class="ad-info"> 
              <h5>{{produto.nome}}</h5> 
              <span>{{produto.descricao_curta}}</span> 
             </div> 
            </div> 
           </li> 
         {% endfor %} 
         </ul> 
        {% else %} 
        <p id="flexiseDemo3"> 
        Nenhum produto encontrado! 
        </p> 
        {% endif %} 

謝謝!