Django - FileField check if None

PythonDjangoDjango Models

Python Problem Overview


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 ?

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPierre de LESPINAYView Question on Stackoverflow
Solution 1 - PythonAdamKGView Answer on Stackoverflow
Solution 2 - PythonKirill VladiView Answer on Stackoverflow