Display only model fields that are non-empty

28 views
Skip to first unread message

Keir Lawson

unread,
Oct 11, 2012, 1:47:00 PM10/11/12
to django...@googlegroups.com
Hello,

I was wondering what the most elegant way (using a DetailView or similar) to display the fields of a model, excluding those that are empty?

Thanks

Keir

Kurtis Mullins

unread,
Oct 11, 2012, 3:33:16 PM10/11/12
to django...@googlegroups.com
There's a couple of ways, assuming you're talking about in the template.

One example would simply be:

{% if object.fieldname %}
{{ object.fieldname }}
{% endif %}

Another example might be:

{{ object.fieldname|default:"" }} 

But it doesn't allow for much formatting of an empty field.

If you want to do this generically, you could take an approach of looping through all fields of a model and checking if each has a value before printing. Something along the lines of this might work for you:


Good luck!



Keir

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To view this discussion on the web visit https://groups.google.com/d/msg/django-users/-/uYV-psryrHcJ.
To post to this group, send email to django...@googlegroups.com.
To unsubscribe from this group, send email to django-users...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

Jonathan Baker

unread,
Oct 11, 2012, 3:40:02 PM10/11/12
to django...@googlegroups.com
I just used the following code on a project to solve the problem you're describing:

models.py
class SomeModel(models.Model):
    ...
    def get_fields(self):
        return [(field.name, field.value_to_string(self)) for field in SomeModel._meta.fields if field.value_to_string(self) is not None]

It's a basic extension to the link that Kurtis just provided.

HTH.
--
Jonathan D. Baker
Developer
http://jonathandbaker.com

Reply all
Reply to author
Forward
0 new messages