2

I have a page set up to load the results of a Django db query into a drop down list. Upon selection of an item, a table is generated with the relavant data.

Given the view method

def index(request):
    parentorg_list = Parentorgs.objects.all()
    context = {'parentorg_list' : parentorg_list}
    return render(request, "app/index.html", context)

and

{% for org in parentorg_list %}
  localStorage.setItem("{{org.parentorg}}", "{{org.parentorgName}}");
{% endfor %}

is there a way to add the items to the localstorage without Django generating ~500 lines of repeated localStorage.setItem()? Or would I be better off in converting the index return to a JSON list for parsing?

Jason
  • 11,263
  • 21
  • 87
  • 181

1 Answers1

5

Make index return a json, something like this:

import json
def index(request):
    parentorg_list = json.dumps([{'key': p.parentorg,'value':p.parentorgName } for p in Parentorgs.objects.all() ]) 
    context = {'parentorg_list' : parentorg_list}
    return render(request, "app/index.html", context)

And in the template loop for the array:

var objects = {{ parentorg_list|escapejs }};
for(var i=0;i < objects.length;i++){
    var obj = objects[i];
    localStorage.setItem(obj.key,obj.value);
}

(I didn't actually tested the code but it should work)

YardenST
  • 5,119
  • 2
  • 33
  • 54