How can I change URL for upladed files?

65 views Asked by At

I have a problem with a path for opening files. I files are saved on s3 amazon, and url for it is https://certsstorenordic.s3.eu-west-3.amazonaws.com/certificate/2022/11/file name.pdf. It opens correct from Django admin. However when i am trying to open it from my website url for it is not correct and is http://127.0.0.1:8000/certificate/2022/11/28/filename.pdf. How to change the beginning of url for uploaded files?

My urls.py:

urlpatterns = []

if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Settings.py:

 WS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.eu-west-3.amazonaws.com'

STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR / 'static'
MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/'

MEDIA_ROOT = BASE_DIR / 'media'

models.py:

certificate = models. FileField(upload_to='certificate/%Y/%m/%d/', blank=True, null=True)

html:

{% for i in response %}
 <tr>
    <td>{{i.component.description}}</td>
     <td><a href="{{ i.certificate }}">Download</a></td>
 </tr>
{% endfor %}
1

There are 1 answers

0
Divya Prakash On

You can use boto3 config to upload your file and that will not add http://127.0.0.1:8000/ to your base URL.

from storages.backends.s3boto import S3BotoStorage

class PublicMediaStorage(S3Boto3Storage):
    location = "media"
    default_acl = "public-read"
    file_overwrite = False
    custom_domain = False

And then use the above class in your model for storage=PublicMediaStorage(). In your case, that will be like

certificate = models. FileField(storage=PublicMediaStorage(), upload_to='certificate/%Y/%m/%d/', blank=True, null=True)