64
You could add a method to your Manors model that will return all the field values, from there you can just loop over these values in your template checking to see if the value isn’t null.
— models.py
class Manors(models.Model)
#field declarations
def get_fields(self):
return [(field.name, field.value_to_string(self)) for field in Manors._meta.fields]
— manor_detail.html
{% for name, value in manor_stats.get_fields %}
{% if value %}
{{ name }} => {{ value }}
{% endif %}
{% endfor %}
8
The following approach only requires defining a single custom template filter (see the docs) – it’s DRY’er than having to write or copy a method into every model you need this functionality for.
— my_app/templatetags/my_tags.py
from django import template
register = template.Library()
@register.filter
def get_fields(obj):
return [(field.name, field.value_to_string(obj)) for field in obj._meta.fields]
You’ll need to restart your server to get the new tags registered and available in your templates.
— my_app/templates/my_app/my_template.html
{% load my_tags %}
<ul>
{% for key, val in object|get_fields %}
<li>{{ key }}: {{ val }}</li>
{% endfor %}
</ul>
Tested in Django 1.11.
NB: Since ._meta is a private attribute it’s functionality might well change in the future.
Thanks to the other answers on this post that took me most of the way, particularly W. Perrin.
- [Django]-How to understand lazy function in Django utils functional module
- [Django]-Django populate() isn't reentrant
- [Django]-Why did Django 1.9 replace tuples () with lists [] in settings and URLs?
0
Use Model._meta.get_fields() in python code.
>>> from django.contrib.auth.models import User
>>> User._meta.get_fields()
(<ManyToOneRel: admin.logentry>,
<django.db.models.fields.AutoField: id>,
<django.db.models.fields.CharField: password>,
<django.db.models.fields.DateTimeField: last_login>,
<django.db.models.fields.BooleanField: is_superuser>,
....
In template, we can define a filter to retrieve all the fields.
├─my_app
│ │
│ ├─templatetags
│ │ │ my_filters.py
│ │
from django import template
register = template.Library()
@register.filter
def get_fields(obj):
return obj._meta.get_fields()
{% for k,v in obj|get_fields %}
<td> {{k}} </td>
{% endfor %}
See this link: https://docs.djangoproject.com/en/2.0/ref/models/meta/#retrieving-all-field-instances-of-a-model
- [Django]-Django access the length of a list within a template
- [Django]-How do I perform query filtering in django templates
- [Django]-Select between two dates with Django