开发者

How to get the fields from object_list in django template

开发者 https://www.devze.com 2023-03-15 18:16 出处:网络
I am using this as Generci view book_info = { \"queryset\" : Book.objects.all(), \"template_name\" : \"book/book_lists.html\",

I am using this as Generci view

book_info = {
    "queryset" : Book.objects.all(),
    "template_name" : "book/book_lists.html",
}

Now in my template book_lists i have

 {% 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. Here is a complete example.

books/models.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:

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

精彩评论

暂无评论...
验证码 换一张
取 消