[英]Use context var to access attribute in django template
我正在构建一个模板来以相同的表格格式呈现多个模型。 我使用基于 class 的列表视图来访问 model。
我还覆盖了上下文以提供每种类型的 model 所需的字段:
视图.py
class ProductListView(ListView):
template_name = 'myApp/table.html'
model = Product
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['fields'] = ['name', 'product_type', 'cost', 'margin']
return context
在模板中,我想循环遍历给定的字段,方法是:
{% for element in object_list %}
<tr>
{% for field in fields %}
<td>{{ element.field }}</td>
{% endfor %}
</tr>
{% endfor %}
但它不显示任何内容。 我在文档( https://docs.djangoproject.com/en/3.1/ref/templates/language/ )中读到:
请注意,像 {{ foo.bar }} 这样的模板表达式中的“bar”将被解释为文字字符串,而不使用变量“bar”的值,如果模板上下文中存在变量“bar”的话。
我明白我做错了什么,但我不知道如何显示这个字段。 我不能只在模板中明确地写出字段名称,因为我希望这个模板能够处理不同的模型。
有没有办法遍历给定的字段?
我刚刚找到了解决方案。 我认为它不是很干净,但它有效:
视图.py
class ProductListView(TemplateView):
template_name = 'myApp/table.html'
def get_context_data(self, *args, **kwargs):
context = super(ProductListView, self).get_context_data(*args, **kwargs)
fields = ['name', 'product_type', 'cost', 'margin']
query_set = Product.objects.all()
context['element_list'] = [[getattr(obj, field) for field in fields] for obj in query_set]
return context
表.html
{% for element in element_list %}
<tr>
{% for field in element %}
<td>{{ field }}</td>
{% endfor %}
</tr>
{% endfor %}
它没有像我计划的那样使用 ListView,但它完成了工作!
可能是这样的:
视图.py
class ProductListView(ListView):
template_name = 'myApp/table.html'
context_object_name = 'products'
def get_queryset(self):
return Product.objects.all()
表.html
{% for product in products %}
<tr>
<td>product.name</td>
<td>product.product_type</td>
<td>product.cost</td>
<td>product.margin</td>
</tr>
{% endfor %}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.