简体   繁体   English

如何在 Django 中显示来自 ajax 搜索结果的产品?

[英]How can display products coming from ajax search result in django?

Problem The search feature is working and the values are retrieved from the Django views search function but now I'm not getting how to display those values in my Django project.问题搜索功能正在运行,值是从 Django 视图搜索功能中检索的,但现在我不知道如何在我的 Django 项目中显示这些值。

Can anyone here can help me through this.这里的任何人都可以帮助我解决这个问题。

The code is attached below.代码附在下面。

JS 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
        }
      });

    }

VIEW看法

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 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 PRODUCT DISPLAY 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 %}

This code gives me the search results but I'm not getting how to show those values here again.此代码为我提供了搜索结果,但我不知道如何再次在此处显示这些值。 This is the home page for products and when I search I want that search result are displayed on the homepage the same way as before.这是产品的主页,当我搜索时,我希望搜索结果以与以前相同的方式显示在主页上。

SEARCH RESULTS IMAGE搜索结果图片在此处输入图片说明

When I use AJAX requests I send the data to a view through get.当我使用 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')
        }
    });
}

In the view I do:在我看来:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM