(Bear with me here, I’ll attempt to explain this as best I can. Please request clarification if desired.)
I’m attempting to create a “hot-or-not”-ish type ranker. I have a set of objects given to me via a Django ValuesQuerySet and run through itertools.combinations() to create pairings. Each pairing is outputted as a tuple of dictionaries, like so:
({'id': 55, 'name': u'Person 1'}, {'id': 63, 'name': u'Person 2'}),
({'id': 55, 'name': u'Person 1'}, {'id': 10, 'name': u'Person 3'}),
({'id': 55, 'name': u'Person 1'}, {'id': 90, 'name': u'Person 4'}),
({'id': 63, 'name': u'Person 2'}, {'id': 10, 'name': u'Person 3'}),
... and so on ...
I’ll be using the rendering the values of these dictionaries in the templates, of course.
The proposed UI for this will display the pictures of each person and await a click from the user. After the click, it’ll load the next pairing until all the pairings have been exhausted.
My JavaScript-fu isn’t great at all, so my questions are these:
-
What is the ideal way to feed jQuery a list of tuples of dictionaries to iterate through? JSON? Nested array? Do something with Django?
-
How would one go about iterating through this array one-by-one after a response from the user (rather than just doing a
jQuery.each()and displaying everything—in addition to providing the opportunity to save a score for the “winning” person to be aggregated once the parings have been exhausted.)?
(Assistance on either or both questions would be greatly appreciated!)
Regarding #1
Without a doubt the best way to get this data from your django view to the javascript in your template is to use
json.dumps()on your list (of tuples, of dictionaries). The result will be a string that you can pass directly to your template. In the template code, you’d then take that value and assign it to a variable:The json module is included in the python stdlib in version 2.6 and up. If you’re running an earlier version, I believe django bundles simplejson (a compatible alternative). Don’t quote me on this since I don’t have a recent django install on my system, but I believe the import path was
from django.utils import simplejson, and perhaps still is.Regarding #2
Making some assumptions here, for the purposes of demonstrating how this could work. Consider the following html fragment (in your template).
We can take this markup, and reuse it as we proceed through the list of person pairs.
There are a few things to setup to accomplish the UI:
Here’s my take on how this could work.