Reputation: 1656
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
Upvotes: 1
Views: 459
Reputation: 174614
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.
Upvotes: 3