How to ensure file exists in Django project?

Question:

My question is simple as the title clearly describes it.

I have FileField in some models, I added a property method to check the existence of file:

@property
def file_exists(self):
    # Because sometimes, the field may contain the string path
    # but the file doesn't exist at all in the server
    if file: # if the string path exists
        return os.path.exists(self.file.path) # If the file exists in server

This works perfectly in development, but when I migrate all my files on AWS, it raises an Error such I don’t have permission to do that.

I wonder what’s wrong, or Is there another way to test whether a file exists?

Asked By: user9865749

||

Answers:

You should use the storage-agnostic Storage.exists() method.

The storage object should be available on the FieldFile itself, so something like

return self.file.storage.exists(self.file.name)

should do the trick.

Answered By: AKX

In Django 3+:

model.file_field.field.storage.exists(model.file_field.name)
Answered By: mrvol

It is also important/safer/faster to check for file name is not None before Storage.exists() method.

def is_file_exists(file_obj):
    return bool(file_obj.name) and file_obj.storage.exists(file_obj.name)
Answered By: pymen