Search code examples
djangoamazon-web-servicesamazon-s3django-storagedjango-compressor

Django compressor and Cloudfront


I use AWS S3 to store my Django static files (using django-storages). And alternate cloudfront domain name to serve these files.

I am unable to finish Django compressor via python manage.py compress.

This is the error I see:

CommandError: An error occurred during rendering /home/ubuntu/foldername/templates/home/xxx.html: 'https://xxx.domainname.com/static/plugins/xxx-xxx/xxx.js' isn't accessible via COMPRESS_URL ('https://s3bucket-static.s3.amazonaws.com/') and can't be compressed

So I tried using the default cloudfront address, alternate domain name and S3 bucket for COMPRESS_URL:

Only https://domainname.com/static/ don't have error. What happen is that after compress is done, the CACHE folder appear inside the local instance staticfiles folder. Which is wrong since I wanted the CACHE folder to be inside the S3 bucket.

Here are my settings for django compressor:

# django-compressor
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    'compressor.finders.CompressorFinder',
)

COMPRESS_ENABLED = True
COMPRESS_OFFLINE = True

if not DEBUG:
    COMPRESS_URL = env('COMPRESS_URL')

Here are my django-storages settings:

if not DEBUG:
    DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
    STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'

    AWS_ACCESS_KEY_ID = env('AWS_ACCESS_KEY_ID')
    AWS_SECRET_ACCESS_KEY = env('AWS_SECRET_ACCESS_KEY')
    AWS_STORAGE_BUCKET_NAME = env('AWS_STORAGE_BUCKET_NAME')

    AWS_DEFAULT_ACL = None
    AWS_CLOUDFRONT_DOMAIN_NAME = env('AWS_CLOUDFRONT_DOMAIN_NAME')
    AWS_S3_CUSTOM_DOMAIN = f'{AWS_CLOUDFRONT_DOMAIN_NAME}.com'

    AWS_S3_OBJECT_PARAMETERS = {
        'CacheControl': 'max-age=86400',
    }
    AWS_LOCATION = 'static'

settings for static files:

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles/')
STATICFILES_DIRS = os.path.join(BASE_DIR, 'static/')

Solution

  • It worked after I changed my django-compressor settings to this:

    # django-compressor
    COMPRESS_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
    
    STATICFILES_FINDERS = (
        'django.contrib.staticfiles.finders.FileSystemFinder',
        'django.contrib.staticfiles.finders.AppDirectoriesFinder',
        'compressor.finders.CompressorFinder',
    )
    
    COMPRESS_ENABLED = True
    COMPRESS_OFFLINE = True
    
    if not DEBUG:
        STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/static/'
        COMPRESS_ROOT = STATIC_ROOT
        COMPRESS_URL = STATIC_URL