How to ensure file exists in Django project?

Hello Awesome People!

My question is simple as the title clearly describes it.

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

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?

Thank you in advance!

Answers 1

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

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


    should do the trick.

Related Articles