Search code examples
djangoamazon-web-servicesamazon-s3boto3django-storage

Getting url after a saving file (not using django model)


I am trying to retrieve the url of a file saved immediately after I have saved it.

Note that I am not using Django model for the file to be saved. I am saving the file manually using default_storage.save(). Obviously with a model it would be easy to retrieve the url.

Currently I have path = default_storage.save(somefile, ContentFile(upload.file.read())) ). I am using AWS Amazon Web Services S3. The files are being saved however I cannot get the url to access the file, I just get back the file name with path. How can I get the url?

If it was locally I could have done something like:

path = default_storage.save(somefile, ContentFile(upload.file.read()))
full_path = os.path.join(settings.MEDIA_ROOT, path)

to get the url/path. Is there anything like that I can do?


Solution

  • Try this

    settings.py
    
    MEDIA_ROOT = URL_BUCKET_S3  #it can be another variable different from MEDIA_ROOT
    

    and the views.py

    path = default_storage.save(somefile, ContentFile(upload.file.read()))
    full_path = settings.MEDIA_ROOT + path
    

    something very similar is how I work in my projects