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

标签 python django templates django-models django-templates

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

我有一个名为 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 返回的每个字段

最佳答案

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

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

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

关于python - Django – 在模板标签中使用模板标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21899350/

相关文章:

python正则表达式不正确匹配

python - 是否可以在 tox 中先运行广度而不是先运行深度?

python - 根据python的结果降序排列一个列表

python - 将 PyTorch 计算机视觉深度学习模型部署到 Windows 桌面应用程序中

javascript - 创建文件,提供下载,单击按钮删除文件,Django 模板

c++ - 模板对象的类访问者模式

c++ - 具有泛型类方法定义的长模板参数列表

c++ - 自定义强制转换不适用于派生类的引用

django - (Django) 创建一个管理命令,它将覆盖 BaseCommand 中的默认设置

python - Django 表格 : cannot call form. 干净