Django default_storage can`t find an existing file
I'm setting up work with my django app, but I ran into a problem when checking for any file in S3 storage.
I can't figure out why I can't use the exists() method in my code. I searched for an error for a long time, but it turned out that the exists() method always returns False to me.
Here is an example:
>>> from django.core.files.storage import default_storage
>>> print(default_storage.listdir(""))
(['media', 'preview'], ['address_preview_1.png','address_preview_35.jpg'])
>>>
>>> print(default_storage.listdir("media"))
([], ['address_preview_35.jpg'])
>>> print(default_storage.exists('address_preview_35.jpg'))
False
>>> print(default_storage.exists('/media/address_preview_35.jpg'))
False
>>> print(default_storage.exists('media/address_preview_35.jpg'))
False
>>> print(default_storage.location)
media
We see that the file "address_preview_35.jpg " there is both in the root of the repository and in the "media" folder.
All arguments in settings.py are configured as described in the documentation. The image files are definitely on the server. We can open it. We can get the image from the full link. We can upload new files to the server and we can delete old ones. We can do everything EXCEPT check whether there is a file on the server or not. What am I doing wrong!?
I tried accessing the server directly and via s3cmd. I tried accessing the repository in the module via
from storages.backends.s3boto3 import S3Boto3Storage
s3_storage = S3Boto3Storage()
print(s3_storage.exists("media/address_preview_35.jpg"))
the result is the same - I see the file in the list, but when checking exists(), I get False.
to enable the required S3 bucket permissions for checking file existence using exists(), follow these steps:
Go to aws iam console:
click users in side bar
select iam user associated for the django app
go to the permissions tab
click add permissions then attach policies
Attach AmazonS3ReadOnlyAccess readonly policy
search for AmazonS3ReadOnlyAccess.
attach it to grant read permissions for all S3 objects.cl
click attach policy
If you already have the permission then you might need to downgrade django-storages[boto3] check here