首页 > 解决方案 > Django模板迭代上下文列表

问题描述

我找不到明确的答案。我有一个显示多个模型的视图。在我的模板中,我已经写出了所有内容以手动显示我想要的内容,但它并没有真正坚持 DRY,所以我想迭代上下文。我找不到的是在我的模板中引用的上下文对象是什么?我在下面的模板片段中编写了我想要实现的伪代码。

编辑简化:模板中的代码在 Django shell 中有效,但在模板中无效

模板.html

{% for object in object_list %}
    {% for key, value in object.items %}
        {% if key == 'string' %}
             <h2>{{ value }}</h2>
        {% endif %}
    {% endfor %}
{% endfor %}

视图.py

class ConfigurationDetailView(LoginRequiredMixin, TemplateView):
    ''' Returns a view of all the models in a configuration '''
    template_name = 'configurator/configuration_detail.html'

    def get_context_data(self, **kwargs):
        ''' Uses a list of dictionaries containing plural strings and models to
        filter by the configuration ID to only show items in the config. '''
        context = super(ConfigurationDetailView, self).get_context_data(**kwargs)
        context_dict = [
            {'string':'integrations', 'model': IntegrationInstance},
            {'string':'control_groups', 'model':  ControlGroup},
            {'string':'endpoints', 'model': Endpoint},
            {'string':'scenes', 'model': Scene},
            {'string':'actions', 'model': Action},
            {'string':'smart_scenes', 'model': SmartScene},
            {'string':'buttons', 'model': Button},
            {'string':'button_actions', 'model': ButtonAction},
        ]
        for item in context_dict:
            for key, value in item.items():
                if key == 'string':
                    string = value
                else:
                    model = value
            context[string] = model.objects.filter(config_id__exact=self.kwargs['config_id'])
        return context

标签: pythondjango

解决方案


默认情况下,上下文由一个名为object_list. 所以你可以像这样迭代

{% for i in object_list %}
  // do something 
{% endfor %}

context_object_name您可以通过在通用视图上定义属性来覆盖变量名称,该属性指定要使用的上下文变量

class MyView(ListView):
    ...
    ...
    context_object_name = "context"

推荐阅读