Using JavaScript to enumerate a dataset returned to a page.

97 views
Skip to first unread message

Lee Stevens

unread,
Jun 19, 2023, 10:30:15 AM6/19/23
to Django users
Helo,

I have a dataset returning to a page.  I need JavaScript to be able to process this.

Instead of using:
{% for item in dataset %}
{{ item.field1 }}
{{ item.field2 }}
{% endfor %}

Is there a JavaScript way to read this dataset/variable instead?

Thanks.

ALBERT ASHABA AHEEBWA

unread,
Jun 19, 2023, 10:36:57 AM6/19/23
to django...@googlegroups.com
Explore using Alpine js. Still learning these bits myself so, I don't have much detail. But Alpine is what you looking for. 



Best Regards,

Albert Ashaba Aheebwa
+256 781 435857

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/37febb44-36e2-47ca-9eff-7011c4e9b963n%40googlegroups.com.

Ryan Nowakowski

unread,
Jun 19, 2023, 11:23:28 PM6/19/23
to django...@googlegroups.com
I assume you're referring to the standard called dataset. If so, take a look here:

https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset#examples

Robin Riis

unread,
Jun 19, 2023, 11:35:01 PM6/19/23
to django...@googlegroups.com
With vanilla js

for(let i = 1; i < myArray.length; i += 1) {
    document.log("index: " + i);
    document.log(myArray[i] + "\n");

Wrote this on my phone so may contain some fault, but a for-loop is sufficent. 

--

Lee Stevens

unread,
Jun 20, 2023, 6:04:29 PM6/20/23
to Django users
So it is sounding more and more like I can't just send in a JSON object and then use JSON.parse to loop through the data.  Maybe I am missing something on the django side.  

Parsing on the JavaScript side is easy, but am I creating the variable {{dataset}} in the original message incorrectly?

Prosper Lekia

unread,
Jun 20, 2023, 6:11:58 PM6/20/23
to django...@googlegroups.com
You can write an Ajax request with Django, and work with the data with JavaScript in the frontend.

--

ivan harold

unread,
Aug 9, 2023, 11:22:42 AM8/9/23
to Django users
1

Have a Django view return a JsonResponse containing your list.

def json_returning_view(request): .... return JsonResponse(data)

You can then use fetch() to get the data, decode it, then display it one by one.

fetch('<your Django endpoint>') .then(response => response.json()) .then(data => data.forEach(item => setInterval(displayItemFunction(), <time in ms>)));
Reply all
Reply to author
Forward
0 new messages