0

This is a simple code created only to show the probem, obviusly the task that this simple code is trying to do can be done without Javascript, but I need to know how I can do this using Javascript, because In my real code I need it, and It cant't be done without Javascript (basically I create a dinamic 2D array with information from the view)

in view.py

in def play_game function

...
players = Player.objects.all()
context = {
    'players' : players
}
return render(request,'play_game.html', context)

in model.py

  class Player(models.Model):

    game = models.ForeignKey(Game, on_delete=models.CASCADE, blank=True, null=True)
    loose = models.IntegerField( default=0)
    win = models.IntegerField(default=0)
    name = models.CharField(max_length=9)

In play_game.html

 <script>
var players = "{{players}}";
for (player in players) {
    document.write(player.name);
    document.write("  Win:"+ player.win); 
    document.write("Loose: " + player.loose); 
};
</script>
4
  • I am using python3 Commented Dec 19, 2016 at 0:35
  • so you want to convert players to json in the templates? Commented Dec 19, 2016 at 0:48
  • I dont't know what that It means. I want to have the object players in the script and use it like a python objetct. Example: Commented Dec 19, 2016 at 0:50
  • I would like to do, var played = player.win + player.loose; Commented Dec 19, 2016 at 0:54

1 Answer 1

2

You need to serialize your data (players).

from django.core import serializers
...
players = serializers.serialize("json", players)
...
return render(request, 'template.html', {'players': players, ...})

and in your template/script

<script>
var players = {{ players || safe }};
players.map(function (player) {
    document.write(player.name);
    document.write("  Win:"+ player.win); 
    document.write("Loose: " + player.loose); 
});
</script>

see SO 1 and SO 2

Sign up to request clarification or add additional context in comments.

1 Comment

and How do I do this ? document.write(player.name); If I do document.write(players); I see: [{"model":"game.game,"fields"{"name":"Bob", "win":3,"loose":2} }]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.