Django - 在模板标签中使用模板标签?

时间:2014-02-20 05:53:58

标签: python django templates django-models django-templates

我正在尝试编写一个简单的Django视图,该视图打印出一个表示模型中所有字段的表。

我有一个名为Menu_Items的模型,有6个字段:

Item_Id
Name
Description
Base_Price
Image_Path
Item_Tags

使用Menu_Items._meta.fields我可以检索字段列表。

对于给定的查询集(例如Menu_Items.objects.all()),我想打印出格式化为表格的所有字段。

我已尝试在上下文中传递字段,但我无法确定要使用的模板标记。是否可以在模板标签内使用模板标签?像这样:

{% for field in fields %}
    {{ menuItems.0.{{ field.name }} }}
    {{ field.name }}
{% endfor %}

在这种情况下,该字段是Menu_Items._meta.fields返回的每个字段

1 个答案:

答案 0 :(得分:3)

而不是这样做,请更改您的查询,使其返回ValueQuerySet values()

您的结果将是一个词典列表,以下是文档中的示例:

>>> Blog.objects.filter(name__startswith='Beatles').values()
[{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}]

现在,在您的模板中:

{% for item in results %}
   {% for column,value in item.iteritems %}
       {{ column }} {{ value }}
   {% endfor %}
{% endfor %}

这将导致:

id 1
name Beatles Blog
tagline All the latest Beatles news.
相关问题