[Fixed]-How to ensure file exists in Django project?

34👍

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.

👤AKX

3👍

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)
👤pymen

1👍

In Django 3+:

model.file_field.field.storage.exists(model.file_field.name)
👤mrvol

Leave a comment