[英]I can't get AWS S3 to serve media files on my Django/Heroku App
堅持了一段時間。 在我的 django 站點的管理頁面中,我可以將照片與我的博客文章一起上傳。 照片將出現在我的 S3 存儲桶中,但不會在博客文章中呈現。 只是一個小照片圖標。
遵循了 simpleisbetterthancomplex 教程,並通讀了我能找到的所有相關的 stackoverflow 問題。 誰能看到我缺少的是什么?
謝謝。
這是我的設置.py:
AWS_ACCESS_KEY_ID = '**********'
AWS_SECRET_ACCESS_KEY = '*********'
AWS_STORAGE_BUCKET_NAME = 'matt-george-portfolio'
AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME
AWS_LOCATION = 'static'
STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION)
AWS_S3_FILE_OVERWRITE = False
AWS_DEFAULT_ACL = None
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
STATIC_URL = '/static/'
MEDIA_URL = '/images/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
import django_heroku
django_heroku.settings(locals())
這是我的存儲桶策略:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "PublicReadGetObject",
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::964481289861:user/my-user"
},
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::my-bucket/*"
},
{
"Sid": "AllObjectActions",
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::964481289861:user/my-user"
},
"Action": "s3:*Object",
"Resource": "arn:aws:s3:::my-bucket/*"
}
]
}
這是我的用戶政策:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": "s3:ListAllMyBuckets",
"Resource": [
"arn:aws:s3:::*"
]
},
{
"Effect":"Allow",
"Action":["s3:ListBucket","s3:GetBucketLocation"],
"Resource":"arn:aws:s3:::my-bucket"
},
{
"Effect":"Allow",
"Action":[
"s3:PutObject",
"s3:PutObjectAcl",
"s3:GetObject",
"s3:GetObjectAcl",
"s3:DeleteObject"
],
"Resource":"arn:aws:s3:::my-bucket"
}
]
}
找出解決方案。 問題不在於我的 settings.py 文件,也不是 IAM、CORS 或存儲桶配置的問題。 我最終遵循了本教程並將 Cloudfront 添加到我的存儲桶中: https://www.ordinarycoders.com/blog/article/serve-django-static-and-media-files-in-production
我的問題的解決方案實際上非常簡單。 我用這樣的標簽調用照片:
{% for post in post_list %}
<div class="img"><img src="{{ post.image }}"></div>
{% endfor %}
但顯然,我忽略了一個事實,即如果圖像來自存儲桶,則需要以不同方式調用圖像。 我在標簽的末尾添加了 .url,所以現在它看起來像這樣:
{% for post in post_list %}
<div class="img"><img src="{{ post.image.url }}"></div>
{% endfor %}
現在我的 django 站點可以毫無問題地提供媒體文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.