Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django DetailView Template show display values of all fields

I made up a template to show all the fields and values from a model, it looks like this:

## detail_template.html ##
{% for name, value in object.get_fields %}
    <p>
        <label>{% trans name %}:</label>
        <span>{{ value|default:"Not available" }}</span>
    </p>
{% endfor %}

In the class you can see the get_fields function declared:

## models.py ##
Class Object:
    ...many fields...

    def get_fields(self):
        return [(field.verbose_name, field._get_val_from_obj(self)) for field in self.__class__._meta.fields]

The problem is, when I have, for example, a CharField with choices, like:

## models.py ##
GENDER_CHOICES = (
    ('M', 'Male'),
    ('F', 'Female'),
)
        ...all other fields ...
    sex =   models.CharField(verbose_name=u"Sex", max_length=1, choices=GENDER_CHOICES)

It displays M or F, what I want to do is load the get_NAMEFIELD_display of all fields without doing manually all fields:

<p>
    <label>{% trans 'Sex' %}:</label>
    <span>{{ object.get_sex_display|default:"Not available" }}</span>
</p>

I have a clue: Django Contrib Admin does that when listing objects, so I'm sure there is a generic way of doing that and I also appreciate any help.

like image 532
staticdev Avatar asked Apr 05 '12 10:04

staticdev


1 Answers

Django >= 2.0

field._get_val_from_obj() is removed in Django 2.0 use field.value_from_object() instead.

Add get_fields() to your models.py:

class Object(Model):
    field1 = CharField(max_length=150)
    field2 = CharField(max_length=150)

    def get_fields(self):
        return [(field.verbose_name, field.value_from_object(self)) for field in self.__class__._meta.fields]

Then call it as object.get_fields on your template.html:

<table>
    {% for label, value in object.get_fields %}
        <tr>
            <td>{{ label }}</td>
            <td>{{ value }}</td>
        </tr>
    {% endfor %}
</table>
like image 86
JV conseil Avatar answered Oct 21 '22 12:10

JV conseil