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;
3
  • You need to serialize that to json to pass to javascript in order for javascript to interpret as valid object Commented Jul 18, 2020 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: stackoverflow.com/q/7165656/7733611 Commented Jul 18, 2020 at 18:29
  • I tried to serialize it and it gives me this error <QuerySet [<TestPRODM: TFT2>, <TestPRODM: TFT2>]> is not JSON serializable Commented Jul 18, 2020 at 18:58

1 Answer 1

-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 %}
Sign up to request clarification or add additional context in comments.

Comments

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.