Django Template JavaScript Passing a Python Variable to a JavaScript One

How do you pass a variable from javascript to python (oTree) or django?

Using live pages seems to solve the issue.

https://otree.readthedocs.io/en/latest/live.html

So in Javascript:

 function sendTracker1() {
liveSend({'which_char': 'char_1', 'value': tracker1})
}

And in Python:

class MyPage(Page):
form_model = 'player'

@staticmethod
def live_method(player, data):
if data['which_char'] == 'char_1':
player.timer_char1 = int(data['value'])


pass queryset data to javascript as a variable template

You can use Django builtin serilizers to pass data to js for queryset.

# views.py
from django.core import serializers

historicals = serializers.serialize("json", Deliveries.objects.all())

# html
<script type="text/javascript">
// construct js objects
var actuals = JSON.parse('{{ historicals | safe }}')
</script>

EDIT

if you would like to loop in django template, you just need to pass delivers queryset, no need parse as js variables.

# views.py
diliveries = Deliveries.objects.all()

# html
{% for i in deliveries %}
{{ i.Date }}
{% endfor %}



Related Topics



Leave a reply



Submit