简体   繁体   English

Django-显示嵌套在html模板列表中的字典中的值

[英]Django - displaying values from a dictionary nested in a list in an html template

I have the followed class-based views in my views.py file: 我的views.py文件中有以下基于类的视图:

class HomeView(TemplateView):
    template_name = 'annual_means/home.html'

    site_list = AnnualMean.objects.values("site").distinct()

    def get_context_data(self, **kwargs):
        context = super(HomeView, self).get_context_data(**kwargs)
        context['sites'] = AnnualMean.objects.values("site").distinct()
        return context

At the top of my html template, just for testing this out, I have {{sites}} and it is displaying: 在我的html模板的顶部,仅出于测试目的,我有{{sites}}并且它显示:

Below, I have the following html code: 下面,我有以下html代码:

{% for value in sites %}
    <li>{{value}}</li>
{% endfor %}   

And it lists all the key:value pairs as shown above, eg {'site': 'Belfast Centre'}, instead of just the values. 并且它列出了上面显示的所有key:value对,例如{'site':'Belfast Centre'},而不仅仅是这些值。 I assume this is due to the dictionary in the QuerySet being nested within a list. 我认为这是由于QuerySet中的字典嵌套在列表中。 Is there a way I can return just the a dictionary or otherwise get around this problem? 有没有办法我可以只返回字典或以其他方式解决这个问题?

I think you should use this as : 我认为您应该将其用作:

{% for value in sites %}
    <li>{{value.site}}</li>
{% endfor %}   

It will now print the values in list 现在它将打印列表中的值

You can access a key in a dictionary using the dot notation : 您可以使用点符号来访问字典中

Dictionary lookup, attribute lookup and list-index lookups are implemented with a dot notation: 字典查找,属性查找和列表索引查找均以点表示法实现:

  {{ my_dict.key }} {{ my_object.attribute }} {{ my_list.0 }} 

For your code, that would be: 对于您的代码,应为:

{% for value in sites %}
    <li>{{value.site}}</li>
{% endfor %}   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM