Django模板对上下文列表进行迭代



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

经过编辑以简化:模板中的代码在Django shell中工作,但在模板中不工作

template.html

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

views.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

默认情况下,上下文由一个名为object_list的变量呈现。所以你可以像一样迭代

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

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

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

最新更新