python - Django - how to display an object's field names and attributes, excluding null ones? -
so have model of there fields might not filled in:
class thing(models.model): name = models.charfield(max_length=300) location = models.charfield(blank=true) comment = models.charfield(blank=true) gallery = models.foreignkey(someotherthing, related_name='things')
i need way display info instance of object in template, showing field names , value of them(only if filled in), so:
the page thing on name: awesome thing location: wisconsin comment: love thing! uploader: joe schmoe
if, example, comment not filled in, want display fields are, not have field name , blank value:
the page thing on name: awesome thing location: wisconsin uploader: joe schmoe
is there kind of way in django? know there kind of method convert object dict, doesn't solve problem of excluding null fields. thanks
you can use model_to_dict
method, , iterate on dictionary this:
{% key, value in dictionary.items %} {% if value %} <p>{{ key }}: {{ value }}</p> {% endif %} {% endfor %}
Comments
Post a Comment