'How to get the json key and value in Django's Templating language?
I'm trying to build a website for tv series using Django framework, I put in the models.py all kinds of details about that show and a JSONField to define the number seasons and episodes in each season.
Example: { "s1" : 15 , "s2" : 25 , "s3" : 23}
I made a dropdown in the template where the series is playing so the user can select the episode
the problem starts when I try to access the values of the keys in the JSON object passed.
I tried that:
{% for key in show.episodes %}
Season {{key}}
{% for value in show.episodes[{{key}}] %}
{{ value }}
{% endfor %}
{% endfor %}
But it this is not working, I assume that the [0] thing in js doesn't work in Django's Templating language, but I cant seem to find any solution.
Solution 1:[1]
You can access the items with the .items() method [python-doc]:
{% for key, value in show.episodes.items %}
Season {{key}}: {{ value }}
{% endfor %}
Solution 2:[2]
You can use {{key.0}}{{key.1}} But for this you have to use list of tupples which is I think is a better option to use in django ... Instead of dictionary
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Willem Van Onsem |
| Solution 2 | Vibhooti Sharma |
