I have a following django code where I return entries queryset:
def search(request):
entries_list = Entry.objects.all()
if request.method == 'GET':
key = request.GET.get('key', False)
entries_list = entries_list.filter(key__icontains=key)
return render(request, 'search.html', {
'entries': entries_list
})
What I would like to do is to print entries (key-value pairs) in my template and to store them in the local storage. How can I do this? I have tried to return JSON or to serialize it but I were not succeded.
Namely, in my javascript (for loop) code I would like to insert my queryset results, instead of some numbers:
{% extends 'base.html' %}
{% block head %}
<script>
var prefix = "localStorage-";
function myFunction() {
alert("Page is loaded");
for(var i = 0; i < 10; i++) {
var key = i// $("#key").attr('value');
var value = 2*i//$("#value").attr('value');
localStorage.setItem(prefix + key, value); //******* setItem()
//localStorage[prefix+key] = value; also works
}
}
</script>
{% endblock %}
{% block body %} onload="myFunction()" {% endblock %}
{% block content %}
{% for e in entries %}
<h3>
<a href="{% url 'article' e.id %}">{{ e.key }}</a>
</h3>
{{ e.value|safe }}
<hr>
{% endfor %}
{% endblock %}
If I understand the question correctly, you want to generate javascript in a Django template?
...
function myFunction()
{
{% for value in entries %}
localStorage.setItem(localStorage-{{ forloop.counter0 }}, {{ value }});
{% endfor %}
}
....
This will yield something like
....
function myFunction()
{
localStorage.setItem(localStorage-0, 'string_version_of_entry_0');
localStorage.setItem(localStorage-1, 'string_version_of_entry_1');
localStorage.setItem(localStorage-2, 'string_version_of_entry_2');
...
}
....
Note that each Entry
will be converted to a string. You can't just transfer Django objects to javascript obviously. How it is converted can be controlled by adding a def __unicode__(self)
to Entry
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With