【问题标题】:How can I change URL for upladed files?如何更改上传文件的 URL?
【发布时间】:2022-11-29 05:37:30
【问题描述】:

我对打开文件的路径有疑问。我的文件保存在 s3 amazon 上,它的 url 是https://certsstorenordic.s3.eu-west-3.amazonaws.com/certificate/2022/11/filename.pdf。它从 Django 管理员正确打开。然而,当我试图从我的网站 url 打开它时,它是不正确的,是 http://127.0.0.1:8000/certificate/2022/11/28/filename.pdf。如何更改上传文件的url开头?

我的网址.py:

网址模式 = []

如果设置。调试: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

设置.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'

模型.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 %}

【问题讨论】:

  • 非常危险的认证吸顶灯作为咖啡机那台服务器肯定有很多问题

标签: django filefield media-url


【解决方案1】:

您可以使用 boto3 配置上传您的文件,这不会将 http://127.0.0.1:8000/ 添加到您的基本 URL。

from storages.backends.s3boto import S3BotoStorage

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

然后在你的model中为storage=PublicMediaStorage()使用上面的类。在你的情况下,就像

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

【讨论】:

    猜你喜欢
    • 2014-08-20
    • 2011-12-24
    • 2012-05-13
    • 1970-01-01
    • 2015-06-06
    • 2022-08-03
    • 2020-06-01
    • 1970-01-01
    • 2017-02-22
    相关资源
    最近更新 更多