How to check ImageField is empty
Asked Answered
B

1

50

I have an ImageField in my model and when I'm saving it I want to check that if it's None or not.

In django shell I'm calling my object's ImageField and it gives :

>>> p.avatar
<ImageFieldFile: None>
>>> p.avatar is None
False

I found that the ImageField's name is u'', so is there any better way to do it ?

Blithering answered 6/3, 2011 at 20:3 Comment(0)
F
88

I found that the ImageField's name is u'', so is there any better way to do it ?

Actually, it looks like that's exactly how this class evaluates bool(), so the better way is to just test its bool() by calling if p.avatar

ImageFieldFile subclasses File, which defines:

def __nonzero__(self):
    return bool(self.name)

So the better way is indeed:

if not p.avatar:
   print "I don't exist"

bool(p.avatar) is False
Finer answered 6/3, 2011 at 20:16 Comment(2)
On template, you should test {% p.avatar != '' %}. Ugly but it works...Prophase
not necessary, you can test simply with {% if p.avatar %} ... {% endif %}Fiume

© 2022 - 2024 — McMap. All rights reserved.