Django - 在模板标签中使用模板标签? [英] Django – Use a template tag within a template tag?
问题描述
我有一个名为Menu_Items的模型,具有6个字段:
Item_Id
名称
描述
Base_Price
Image_Path
Item_Tags
使用 Menu_Items._meta.fields
I可以检索字段列表。
对于给定的查询器(例如 Menu_Items.objects.all()
)I想打印所有字段,格式化为表格。
我已经尝试在上下文中传递字段,但是我无法弄清楚哪个模板标签使用。是否可以在模板标签内部使用模板标签?如下所示:
{%for fields in fields%}
{{menuItems.0。{{field.name }}}}
{{field.name}}
{%endfor%}
在这种情况下,该字段是Menu_Items._meta.fields返回的每个字段
而不是这样做,更改您的查询,以便返回 ValueQuerySet
与 values()
。
您的结果将是词典列表,以下是文档中的示例:
>>> blog.objects.filter(name__startswith ='Beatles')。values()
[{'id':1,'name':'披头士博客','标语':'所有最新的披头士乐队新闻。 ]
现在,在你的模板中:
{%for results in results%}
{%for column,value in item.iteritems%}
{{column}} {{value}}
{%endfor%}
{%endfor%}
这将导致:
id 1
name披头士博客
标语所有最新的披头士乐队新闻。
I am trying to write a simple Django view that prints out a table representing all the fields in a model.
I have a model called Menu_Items, with 6 fields:
Item_Id
Name
Description
Base_Price
Image_Path
Item_Tags
Using Menu_Items._meta.fields
I can retrieve the list of fields.
For a given queryset (e.g. Menu_Items.objects.all()
) I would like to print out all of the fields, formatted as a table.
I've tried passing the fields in the context, but I cannot figure out which template tag to use. Is it possible to use a template tag inside of a template tag? like so:
{% for field in fields %}
{{ menuItems.0.{{ field.name }} }}
{{ field.name }}
{% endfor %}
In this case, the field is each of the fields returned by Menu_Items._meta.fields
Instead of doing this, change your query so it returns a ValueQuerySet
with values()
.
Your result will be a list of dictionaries, here is an example from the documentation:
>>> Blog.objects.filter(name__startswith='Beatles').values()
[{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}]
Now, in your template:
{% for item in results %}
{% for column,value in item.iteritems %}
{{ column }} {{ value }}
{% endfor %}
{% endfor %}
This will result in:
id 1
name Beatles Blog
tagline All the latest Beatles news.
这篇关于Django - 在模板标签中使用模板标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!