Home > OS >  Displaying a dictionary value from django model in a html
Displaying a dictionary value from django model in a html

Time:10-22

I have a django model that consists of a JSONField(). What I am trying to do is pass the details of this field to html, by the form of a context variable. The JSONField() stores a dictionary. For some reason the I only the first part of each dictionary element shows up in the presented html file.

Models.py:

class WholeValues(models.Model):
    eb_top_items_list = models.JSONField()

Main.py

#updating JSONField() values with a dictionary
eb_numbers_for_upload = WholeValues.objects.all()
eb_numbers_for_upload.update(eb_top_items_list=df_eb_values.head(n=6).to_dict())

html

<ul>
    {% for item in eb_top_items %}
    <ul> {{ item }}</ul>
    {% endfor %}
</ul>

So the dictionary that is in my .JSONField() looks as follows

 {'ElectricBikeA': 13, 'ElectricBikeB': 12, 'ElectricBikeC': 11, 'ElectricBikeD': 11, 'ElectricBikeE': 7} 

However displayed on the page is only the text part of the dictionary. what is displayed is missing the number values. All it has is ElectricBikeA, ElectricBikeB....etc

So i guess the real question is how can I get a context variable to show the values of the dictionary as well as the name?

CodePudding user response:

Use dict.items() to loop through the keys and values of the dict as pairs

<ul>
    {% for key, value in eb_top_items.items %}
    <ul>{{ key }}: {{ value }}</ul>
    {% endfor %}
</ul>
  • Related