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
I’m not sure if Django has anything specific for this, but you can always:
Define the data model you are working with in your JS
json.dumps(your_dict)
from python and return the resulting stringjson.parse(resulting_str)
the string into the object you modeled in JSThis should give you a javascript object.
Just remember that json.parse() can throw an error
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
srs/learn.js
Template remains the same.
An alternative would be to use Django
serialization
. Here is anexample
.