[英]How to get the fields from object_list in django template
I am using this as Generci view我将其用作 Generci 视图
book_info = {
"queryset" : Book.objects.all(),
"template_name" : "book/book_lists.html",
}
Now in my template book_lists i have现在在我的模板 book_lists 我有
{% for book in object_list %}
<tr>
<td>{{ book.name }}</td>
Is there any way i can loop through all like we have in form有什么办法可以像我们在表格中一样循环遍历所有内容
{% for field in form %}
forn.label_tag and field
so that i can use it for all Models这样我就可以将它用于所有模型
so basically i want something like所以基本上我想要类似的东西
{% for obj in object_list %}
<tr>
{% for fields in obj %}
<td> {{field.name}}:{{field}} </td>
You need to create a get_fields function in your model(s) which you can then use in the templates to access the fields and values generically.您需要在模型中创建一个 get_fields function,然后您可以在模板中使用它来一般地访问字段和值。 Here is a complete example.
这是一个完整的例子。
books/models.py:书籍/模型.py:
from django.db import models
class Book(models.Model):
name = models.CharField(max_length=30)
author = models.CharField(max_length=30)
isbn = models.IntegerField(max_length=20)
published = models.BooleanField()
def get_fields_and_values(self):
return [(field, field.value_to_string(self)) for field in Book._meta.fields]
templates/books/book_list.html:模板/书籍/book_list.html:
<table>
{% for obj in object_list %}
<tr>
{% for fld, val in obj.get_fields_and_values %}
<td>{{ fld.name }} : {{ val }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.