最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - Issue with Loading Static Files and Images from Amazon S3 in Django - Stack Overflow

programmeradmin9浏览0评论
# Amazon S3 Configuration
AWS_ACCESS_KEY_ID = "<your-access-key-id>"
AWS_SECRET_ACCESS_KEY = "<your-secret-access-key>"
AWS_STORAGE_BUCKET_NAME = "<your-bucket-name>"
AWS_S3_REGION_NAME = "us-east-2"
AWS_S3_CUSTOM_DOMAIN = f"https://{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws"

AWS_S3_OBJECT_PARAMETERS = {"CacheControl": "max-age=86400"}
AWS_S3_QUERYSTRING_AUTH = False

# STORAGES Configuration
STORAGES = {
    "default": {
        "BACKEND": "storages.backends.s3boto3.S3Boto3Storage",
            "OPTIONS": {
            "location": "media",  # Directory for media files
            "file_overwrite": False,  # Prevent overwriting files
        },
    },
    "staticfiles": {
        "BACKEND": "storages.backends.s3boto3.S3StaticStorage",
        "OPTIONS": {
            "location": "static",  # Directory for static files
        },
    },
 }

# Configuration during development
STATIC_URL = "/static/"  # URL for static files
STATICFILES_DIRS = [BASE_DIR / "config" / "static"]  # Directories for static files
STATIC_ROOT = BASE_DIR / "staticfiles"  # Root directory for collected static files

MEDIA_URL = "/media/"  # URL for media files
MEDIA_ROOT = os.path.join(BASE_DIR, "media")  # Root directory for media files

# S3 Configuration for production
if not DEBUG:
    STATIC_URL = f"{AWS_S3_CUSTOM_DOMAIN}/static/" 
    MEDIA_URL = f"{AWS_S3_CUSTOM_DOMAIN}/media/" 

The documentation used was from .html.

I am using Django version 5.1.4 and the PythonAnywhere server.

Although the static files (CSS, JS, assets) are being collected correctly, when accessing the application, the layout is broken, with no styles applied or images loaded from the static/assets folder.

Could anyone help me resolve this issue and ensure that the static files are loaded correctly in the production environment?

# Amazon S3 Configuration
AWS_ACCESS_KEY_ID = "<your-access-key-id>"
AWS_SECRET_ACCESS_KEY = "<your-secret-access-key>"
AWS_STORAGE_BUCKET_NAME = "<your-bucket-name>"
AWS_S3_REGION_NAME = "us-east-2"
AWS_S3_CUSTOM_DOMAIN = f"https://{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws"

AWS_S3_OBJECT_PARAMETERS = {"CacheControl": "max-age=86400"}
AWS_S3_QUERYSTRING_AUTH = False

# STORAGES Configuration
STORAGES = {
    "default": {
        "BACKEND": "storages.backends.s3boto3.S3Boto3Storage",
            "OPTIONS": {
            "location": "media",  # Directory for media files
            "file_overwrite": False,  # Prevent overwriting files
        },
    },
    "staticfiles": {
        "BACKEND": "storages.backends.s3boto3.S3StaticStorage",
        "OPTIONS": {
            "location": "static",  # Directory for static files
        },
    },
 }

# Configuration during development
STATIC_URL = "/static/"  # URL for static files
STATICFILES_DIRS = [BASE_DIR / "config" / "static"]  # Directories for static files
STATIC_ROOT = BASE_DIR / "staticfiles"  # Root directory for collected static files

MEDIA_URL = "/media/"  # URL for media files
MEDIA_ROOT = os.path.join(BASE_DIR, "media")  # Root directory for media files

# S3 Configuration for production
if not DEBUG:
    STATIC_URL = f"{AWS_S3_CUSTOM_DOMAIN}/static/" 
    MEDIA_URL = f"{AWS_S3_CUSTOM_DOMAIN}/media/" 

The documentation used was from https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html.

I am using Django version 5.1.4 and the PythonAnywhere server.

Although the static files (CSS, JS, assets) are being collected correctly, when accessing the application, the layout is broken, with no styles applied or images loaded from the static/assets folder.

Could anyone help me resolve this issue and ensure that the static files are loaded correctly in the production environment?

Share Improve this question edited Mar 27 at 12:04 Victor Reginaldo asked Mar 27 at 11:59 Victor ReginaldoVictor Reginaldo 213 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

I managed to solve the issue, but I'll leave the question here with my solution in case someone encounters the same problem:

Steps for S3 Bucket Configuration:

Check the permissions of your bucket:

  • Disable all options in "Block public access" (bucket settings).

  • Add the following policy to your bucket (replace your_bucket with your actual bucket name):

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::your_bucket/media/*"
        }
    ]
}

CORS (Cross-Origin Resource Sharing) Configuration: Add the CORS configuration to allow the necessary access:

[
    {
        "AllowedHeaders": [
            "*"
        ],
        "AllowedMethods": [
            "GET",
            "POST",
            "PUT",
            "DELETE"
        ],
        "AllowedOrigins": [
            "*"
        ],
        "ExposeHeaders": []
    }
]

Configuration in Django:

Here are the necessary settings to integrate S3 for storing media and serving static files through your server (like PythonAnywhere):

# Amazon S3 configuration for media
AWS_ACCESS_KEY_ID = "your_access_key_id"
AWS_SECRET_ACCESS_KEY = "your_secret_access_key"
AWS_STORAGE_BUCKET_NAME = "your_bucket"
AWS_S3_REGION_NAME = "your_region"

AWS_S3_OBJECT_PARAMETERS = {"CacheControl": "max-age=86400"}
AWS_S3_QUERYSTRING_AUTH = False

# Storage configuration for S3 for media
DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage"
STATICFILES_STORAGE = "django.contrib.staticfiles.storage.StaticFilesStorage"

# Static and media directories
STATIC_URL = "/static/"
STATIC_ROOT = BASE_DIR / 'staticfiles'
STATICFILES_DIRS = [BASE_DIR / "config" / "static"]  # Static files folder on the server

# In production, serve static files locally and media through S3
if not DEBUG:
    STATIC_URL = "/static/"
    MEDIA_URL = f"https://{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws/media/"

With these configurations, static files will be served by PythonAnywhere, while media files will be managed by Amazon S3.

My issue was caused by the AWS_S3_CUSTOM_DOMAIN variable. Although I couldn’t pinpoint the exact error, I suspect it’s related to the SSL certificate. My suggestion is to avoid customizing the URL and leave that configuration to AWS, allowing it to manage the domain automatically.

发布评论

评论列表(0)

  1. 暂无评论