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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With