Django – FileField check if None

Question:

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 ?

Asked By: Pierre de LESPINAY

||

Answers:

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.

Answered By: AdamKG

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)
Answered By: Kirill Vladi
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.