Lucifer N.
Lucifer N.

Reputation: 1056

Django - how to display an object's field names and attributes, excluding null ones?

So say I have a model of which there are some fields that might not be 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 a way to display the info about an instance of this object in a template, showing the field names and the value of them(only if it is filled in), like so:

The page with the thing on it

name: my awesome thing
location: wisconsin
comment: love this thing!
uploader: joe schmoe

if, for example, comment were not filled in, I would only want to display the fields that are, not have the field name and a blank value:

The page with the thing on it 
name: my awesome thing
location: wisconsin
uploader: joe schmoe

Is there some kind of way to do this simply in django? I know there is some kind of method to convert an object into a dict, but this doesn't solve the problem of excluding null fields. Thanks

Upvotes: 0

Views: 58

Answers (2)

Eugene Soldatov
Eugene Soldatov

Reputation: 10145

thing = Thing.objects.get(pk=1)
for field_name in Thing._meta.get_all_field_names():
    if getattr(thing, field_name):
        print field_name, getattr(thing, field_name)

Upvotes: 0

knbk
knbk

Reputation: 53699

You can use the model_to_dict method, and iterate over the dictionary like this:

{% for key, value in dictionary.items %}
  {% if value %}
    <p>{{ key }}: {{ value }}</p>
  {% endif %}
{% endfor %}

Upvotes: 2

Related Questions