0

Here is my view.py :

def get_group_ajax(request):
    if request.method == "GET":
        g_id = request.GET['group_id']
        productlist = models.Stocksupporter.objects.filter(pmaingroups = g_id).values('productname').exclude(numberqut=0) *//This is my queryset*

Here is my AJAX and used Django template for loop :

$("#allgrp").change(function () {
    const gId = $('#allgrp').val();

    $.ajax({
      type: "GET",
      url: '{% url "webapp:get_group_ajax" %}',
      data: {
        'group_id': gId,
      },
      success: function (data) {
          html_data = 
          `
          {% for pr in productlist %}
          <div class="cardc" id="card_id">
            <p>{{ pr.productname }}</p>
          </div>
          {% endfor %} 
           `;
         
          $("#card_id2").html(html_data);
      }
    });
  });

now what is problem: I want return productlist (for loop) in AJAX Success based on selected value (mean group id), i used Response methods but still can not return anything. is there any way for do it?

3
  • I think you do not understand something ? Your template is rendering one time when you display your page and all django template tags and filter is proceessed at this time. Your ajax call will trigger after this rendering so you can put only javascript code into the success function Commented Nov 16, 2022 at 7:59
  • After display your page, right click > source code and you will understand the problem i guess Commented Nov 16, 2022 at 8:01
  • @LucasGrugru , which js code is should put in success that can filter list based on selected group id? Commented Nov 16, 2022 at 8:07

1 Answer 1

1

views.py :

from django.http import JsonResponse

if 'group_id' in request.GET:
    productlist = Stocksupporter.objects.filter(pmaingroups = g_id).exclude(numberqut=0).values('productname')
    return JsonResponse(list(productlist ),safe=False)

Success function in html:

function(productListData){
   for(i in productListData){
     let element = ` <div class="cardc">
        <p>${productListData[i].productname}</p>
      </div>`
      $("#card_id2").append(element);
    }
 }
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for answer. is this put any item in list sperated dives? or put all of list in one div?
It creates new div for each item.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.