1

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.

2 Answers2

1

You can access the items with the .items() method [python-doc]:

{% for key, value in show.episodes.items %}
    Season {{key}}: {{ value }}
{% endfor %}
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • cool, but what I mean is that I want to call the number of episodes of the second season. in js I would do episodes[1].value how do i do that in Django templating language? I tried show.episodes.items[1] which surly didn't work – Youssef Ihab Apr 03 '22 at 18:48
  • something like the zip() function in python – Youssef Ihab Apr 03 '22 at 18:59
  • 1
    @YoussefIhab: `episodes` is a dictionary and the keys are strings, hence, `episodes[1]` makes no sense, but you can use ``show.episodes.s1` here to access the value for `s1`, subscripting is *deliberately* restricted in the template language to prevent people from wrting business logic in the template. – Willem Van Onsem Apr 03 '22 at 18:59
0

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