【问题标题】:How can display products coming from ajax search result in django?如何在 django 中显示来自 ajax 搜索结果的产品?
【发布时间】:2021-09-16 20:14:02
【问题描述】:

问题 搜索功能正在工作,并且从 Django 视图搜索功能中检索了值,但现在我不知道如何在我的 Django 项目中显示这些值。

这里的任何人都可以帮助我解决这个问题。

代码附在下面。

JS

 $('#searchsubmit').on('click', function(e){
        e.preventDefault();
        q = $('#search').val();
        console.log(q);
        updateContentBySearch(q);
  });

function updateContentBySearch(q) {
    var data = {};
    data['search_by'] = q
    // data["csrfmiddlewaretoken"] = $('#searchform [name="csrfmiddlewaretoken"]').val();
    $.ajax({
        url: "{% url 'main:Search' %}",
        data: {
          'search_by': q
        },
        success: function (data) {
            // do your thing
        }
      });

    }

查看

def search(request):
    q = request.GET.get('search_by')
    print(q)
    product = Products.objects.all()
    cart_product_form = CartAddProductForm()
    transaction = transactions.objects.filter(productID__name__icontains=q,status='Enable').order_by('productID')
    print(transaction)
    return HttpResponseRedirect(reverse('main:home'),{'products':product, 'transaction': transaction , 'cart_product_form':cart_product_form})
    # return redirect(request, 'main/home.html',{'products':product, 'transaction': transaction , 'cart_product_form':cart_product_form})

HTML 表单

form class="d-flex col-md-6" id="searchform">
   <div class="input-group mb-3" style="text-align:center">
  <input name="q" type="text" class="form-control" placeholder="Search" id="search">
  <button class="btn btn-primary shadow px-5 py-2" type="submit" id="searchsubmit">Search</button>
   </div>
</form>

HTML 产品展示

 {% regroup transaction by productID as ProductList %}
  {% for productID in ProductList %}
  <div class="col-sm-3 productID" >
    <div class="product">
      <a href="{% url 'main:product-detail' productID.grouper.id %}" class="img-prod"><img class="img-fluid" src={{productID.grouper.product_image.url}} alt="" height="200px">
        <span class="status id_discount">%</span>
        <div class="overlay"></div>
      </a>
      <div class="text py-3 pb-4 px-3 text-center">
        <h3><a href="#">{{productID.grouper}}</a></h3>
        <div class="d-flex text-center">
          <div class="" style="width: 310px;">
            <p class="price"><span class="mr-2 price-dc id_price"> </span> Rs. <span class="price-sale"> </span></p>
          </div>
        </div>
          
         
         
        <!-- <div class="bottom-area d-flex px-3">
          <div class="m-auto d-flex"> -->
            <form id='transactionIDValue' class="d-inline" method="post">
              <div class="row">
                <select class="col-md-8 form-select tranactionID" id="ItemID" style="">
                  {% for val in productID.list %}
                      <option transID={{val.id}} price={{val.Price}} discount={{val.discount_percentage}} sale_price={{val.get_sale}} class="price_value" >{{val.AUID}} - {{val.Description}}</option>
                  {% endfor %}
                </select>
              <div class="col-md-4">
              {{cart_product_form.quantity}}
            </div>
              {% csrf_token %}
              <hr style="border-top: 1px solid #ccc; background: transparent;">
              <input type="submit" class="btn btn-primary shadow px-5 py-2 Id_submit" value="Add To Cart">
              <!-- <button type="submit" class="btn btn-primary shadow px-5 py-2">Add to Cart</button> -->
            </form>
            
          </div>
          <!-- </div>
        </div> -->
      </div>
    </div>
  </div>
  {% endfor %}

这段代码给了我搜索结果,但我不知道如何在这里再次显示这些值。这是产品的主页,当我搜索时,我希望搜索结果以与以前相同的方式显示在主页上。

搜索结果图片

【问题讨论】:

    标签: html django ajax django-views django-templates


    【解决方案1】:

    当我使用 AJAX 请求时,我通过 get 将数据发送到视图。

    function get_data(query) {
        $.ajax({
            url: '{% url 'your view' %}',
            dataType: 'json',
            data: {
                'query': query,
            },
            success: function (data) {
                if (!data.error) {
                    if (data.items.length > 0) {
            var $html_content = '';
                        for (var $i = 0; $i < data.items.length; $i++) {
                            $contact_data += '<tr>';
    
                            # Format HTML ($html_content += 'your html from data';
                        }
                    }
    
                    $('#contact_content').html($html_content );
                    $('#navigation').html(data.page.render);
    
                } else {
                    console.log(data.error_message);
                }
            },
            error: function () {
                console.log('Couldnt collect data')
            }
        });
    }
    

    在我看来:

    def get_items(request):
    data = {'error': True}
    
    try:
        query = int(request.GET.get('query', None))
    except:
        query = None
    
    if query:
        data['error'] = False
    data['items'] = [] #list with your data
    else:
        data['error_message'] = 'No valid page index was given'
    
    return JsonResponse(data)
    

    【讨论】:

      猜你喜欢
      • 2016-06-26
      • 1970-01-01
      • 1970-01-01
      • 2021-03-30
      • 2021-09-17
      • 1970-01-01
      • 1970-01-01
      • 2019-11-09
      • 2018-09-29
      相关资源
      最近更新 更多