Django显示嵌套在html临时文件列表中的字典中的值

2024-09-29 19:24:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下基于类的观点视图.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

在我的html模板的顶部,为了测试这一点,我有{{sites}},它显示:

下面,我有以下html代码:

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

它列出了所有键:值对如上图所示,例如{'site':'Belfast center'},而不仅仅是值。我假设这是因为QuerySet中的字典嵌套在一个列表中。有没有什么方法可以让我把字典里的东西还给你,或者解决这个问题?你知道吗


Tags: selfdatagetobjectsvaluehtmlcontextsite
2条回答

我想你应该用这个作为:

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

它现在将打印列表中的值

您可以访问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 value in sites %}
    <li>{{value.site}}</li>
{% endfor %}   

相关问题 更多 >

    热门问题