Serving Django's static and media files from S

2019-04-29 04:49发布

问题:

I'm having a weird problem and I have no idea what's causing it. Here's my current config (using Heroku):

MEDIA_URL = '/media/'
STATIC_URL = '/static/'

STATICFILES_DIRS = (
os.path.join(PROJECT_DIR, '../static'),
)

#Determine if local or deployed.
if 'DATABASE_URL' in os.environ:
    STATICFILES_STORAGE     = 'storages.backends.s3boto.S3BotoStorage'
    AWS_ACCESS_KEY_ID       = 'A...A' 
    AWS_SECRET_ACCESS_KEY   = '...R' 
    DEFAULT_FILE_STORAGE    = 'storages.backends.s3boto.S3BotoStorage'

    # PRODUCTION OR STAGING
    if 'PROD' in os.environ:
        AWS_STORAGE_BUCKET_NAME = 's3.project.com'
        STATIC_URL = "https://s3.amazonaws.com/project/"
    else:
        AWS_STORAGE_BUCKET_NAME = 'project-staging'
        STATIC_URL = "https://s3.amazonaws.com/project-staging/"
else:
    STATIC_ROOT = ''

The thing is, static files are working fine, the links look like this: https://s3.amazonaws.com/project-staging/img/homepage_left.png.

First problem (Admin half broken):

The admin is half working. CSS files are served fine: https://project-staging.s3.amazonaws.com/admin/js/core.js?Signature=asdasdasd%3D&Expires=1352430664&AWSAccessKeyId=asdasdasA but the all the images are broken:

https://project-staging.s3.amazonaws.com/admin?Signature=%2asdasdad%3D&Expires=1352430664&AWSAccessKeyId=asdasdaimg/icon_calendar.gif

I don't know why the Signature and AWSAccesskey are there :(. If I remove them (by hand) the URL works fine!

Second problem (uploaded media via ImageField/FileField):

I'm using {{MEDIA_URL}}{{object.flyer}}, it translates to /media/media/flyers/poster_1.png, how do I point it out to s3? It should be like this: https://project-staging.s3.amazonaws.com/media/flyers/poster_1.png

回答1:

Answer to your second question: you need to set MEDIA_URL = https://project-staging.s3.amazonaws.com/media/ just like you're doing for STATIC_URL



回答2:

For your first question, I think you need to do:

AWS_QUERYSTRING_AUTH = False