python - 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
解决方案
默认情况下,上下文由一个名为object_list
. 所以你可以像这样迭代
{% for i in object_list %}
// do something
{% endfor %}
context_object_name
您可以通过在通用视图上定义属性来覆盖变量名称,该属性指定要使用的上下文变量
class MyView(ListView):
...
...
context_object_name = "context"
推荐阅读
- python - RPI 伺服帽子 python3 库抛出错误:“板”没有属性“SCL”
- ruby-on-rails - 如何在 Ruby on Rails 上使用 will_paginate gem 实现 Ajax
- python - 为什么我的“cat”语句在我的 Python for 循环中不起作用?
- android - Android 房间:LiveData 上的调用值可以用来返回纯数据吗?
- lua - 如果我迅速获得战利品然后离开,为什么这个 roblox 脚本不会保存?
- python - 从 excel/csv 表中提取特定值以在 Python 中形成另一个表
- c++ - C++项目使用Sqlite数据库如何发布或部署?
- javascript - 使用 AutoComplete JQuery (ASP.NET, C#) 时如何单击以进行选择
- scala - 在 unapply 中找不到 Scala 无形 Generic.Aux 隐式参数
- javascript - 开始使用客户端创建的 Oauth2 授权