skip to Main Content

I have a dictionary called cards, which I have created from my Card model. Each card has a front and back property. I think I am importing the ‘cards’ dictionary into my JS file from the template correctly. But I am unsure on how to access the vales from the dictionary, and how to display the values without any {,[,’ etc.

I did previously try having 2 different arrays: one for the fronts of the cards, one of the backs of the cards. However, I have a feeling this could get messy later on. Either way, it would be useful to know how to display python dictionaries in JS.

models.py:

from django.db import models

class Deck(models.Model):
    name = models.CharField(max_length=50)
    
    def __str__(self):
        return self.name

class Card(models.Model):
    front = models.CharField(max_length=200)
    back = models.CharField(max_length=200)
    deck = models.ForeignKey(Deck, on_delete=models.CASCADE, related_name='cards')
    
    def __str__(self):
        return self.front

view function:

def learn(request, deck_id):
    deck = get_object_or_404(Deck, pk=deck_id)
    cards_queryset = deck.cards.all()
    cards = [{'front': card.front, 'back': card.back} for card in cards_queryset]
    
    
    return render(request, 'srs/learn.html', {
        'deck': deck,
        'cards': cards,
    })

template file:

{% extends "srs/layout.html" %}
{% load static %}

{% block body %}
    <div class="body-container">
        <p class="front"></p>
        <p class="back"></p>
        <button id="show-answer">Show Answer</button>
        <button id="next-card">Next</button>

    </div>

    <div id="cards-var" data-cards="{{ cards }}"></div>
    <script src="{% static 'srs/learn.js' %}"></script>
{% endblock %}

Thank you!

2

Answers


  1. I’m not sure if Django has anything specific for this, but you can always:

    1. Define the data model you are working with in your JS

    2. json.dumps(your_dict) from python and return the resulting string

    3. json.parse(resulting_str) the string into the object you modeled in JS

    This should give you a javascript object.

    Just remember that json.parse() can throw an error

    Login or Signup to reply.
  2. JavaScript cannot load neither a QuerySet nor a Python Dict. As our friend kindly pointed out, you need to transform data to a format that JavaScript is able to load, in this case JSON.

    You can use model_to_dict form helper function to extract the wanted fields instead of doing it manually, also making the code more readable.

    views.py

    from django.forms import model_to_dict
    import json
    
    
    def learn(request, deck_id):
        deck = get_object_or_404(Deck, pk=deck_id)
        qs = deck.cards.all()
        cards = [model_to_dict(instance, fields=["front", "back"]) for instance in qs]
    
        return render(
            request,
            "srs/learn.html",
            {
                "deck": deck,
                "cards": json.dumps(cards),
            },
        )
    

    srs/learn.js

    document.getElementById("show-answer").addEventListener("click", (event) => {
      const data = document.getElementById("cards-var").dataset.cards;
      const cards = JSON.parse(data);
      console.log(cards[0]);
    });
    

    Template remains the same.

    An alternative would be to use Django serialization. Here is an example.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search