0

I have a data list in Html. from Django views.py as a tag (Mydata).

and In the HTML page I want to loop through that list using Jquery

I tried some method but it didn't work this is my view

def weltestprd(request, WeelN):
    MyData=TestPRODM.objects.filter(WellID__exact=WeelN)
    context={
    'MyData':MyData,
    }
    return render(request,'Home/Prodtest.html',context)

and this is my HTML page and the loop works fine.

{% for Values in MyData %}
    <p>{{Values.Id}}</p>
    <p>{{Values.Name}}</p>
    <p>{{Values.Prod}}</p>    <!-- decimal number-->
{% endfor %}

and I want to see the same result in consol using jquery I tried this but didn't work by the way I have (string and decimal number in my list)

{% block custom_js %}
<script >
var my_dataLoop = ("{{ MyData }}")

console.log(my_dataLoop)

$.each(my_dataLoop, function(key, value) {
  console.log(value);
})

</script>
{% endblock custom_js %}

the console.log(my_dataLoop) shows me this list without numbers?

&lt;QuerySet [&lt;TestPRODM: TFT2&gt;, &lt;TestPRODM: TFT2&gt;]&gt;
Shatish Desai
  • 575
  • 6
  • 20
tibas
  • 139
  • 13
  • You need to serialize that to json to pass to javascript in order for javascript to interpret as valid object – charlietfl Jul 18 '20 at 18:22
  • In your code, MyData is a QuerySet object in python. As charlietfl said, it needs to be converted to a structure javascript can work with. Check this SO post: https://stackoverflow.com/q/7165656/7733611 – user3750325 Jul 18 '20 at 18:29
  • I tried to serialize it and it gives me this error , ]> is not JSON serializable – tibas Jul 18 '20 at 18:58

1 Answers1

-1

You cant loop the Django Queryset object using jquery. What you can do is loop using django and print using jquery. The code is not exact, but it may looks something like this:

{% block custom_js %}
  <script >
    {% for Values in MyData %}
      console.log("Id: " + {{Values.Id}} + ", Name: " + {{Values.Name}} + ", Prod: " + {{Values.Prod}});
    {% endfor %}
  </script>
{% endblock custom_js %}
Siva Sankar
  • 1,672
  • 1
  • 9
  • 16