83

I have a model with an optional file field

class MyModel(models.Model):
  name = models.CharField(max_length=50)
  sound = models.FileField(upload_to='audio/', blank=True)

Let's put a value

>>> test = MyModel(name='machin')
>>> test.save()

Why do I get that ?

>>> test.sound
<FieldFile: None>
>>> test.sound is None
False

How can I check if there is a file set ?

Pierre de LESPINAY
  • 44,700
  • 57
  • 210
  • 307

2 Answers2

122
if test.sound.name: 
     print "I have a sound file"
else:   
     print "no sound"

Also, FileField's boolean value will be False when there's no file: bool(test.sound) == False when test.sound.name is falsy.

Akaisteph7
  • 5,034
  • 2
  • 20
  • 43
AdamKG
  • 13,678
  • 3
  • 38
  • 46
0

According to this answer from a different question, you can try this:

class MyModel(models.Model):
  name = models.CharField(max_length=50)
  sound = models.FileField(upload_to='audio/', blank=True)

def __nonzero__(self):
    return bool(self.sound)
Daniel Holmes
  • 1,952
  • 2
  • 17
  • 28
Kirill Vladi
  • 484
  • 6
  • 14