
To store Django static and media files on Amazon S3, you can use the django-storages
package, which provides a custom storage backend for various file storage services including Amazon S3. Here's a step-by-step guide on how to set it up:
Install
django-storages
:
pip install django-storages
Configure your Django settings:
# settings.py
# Import necessary modules
import os
from storages.backends.s3boto3 import S3Boto3Storage
# Set the required AWS credentials
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 = 'your-region-name' # e.g. us-west-2
# Optional: Set custom domain for static and media files
# AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com'
# Set the static and media files locations
STATICFILES_LOCATION = 'static'
MEDIAFILES_LOCATION = 'media'
# Define custom storage classes for static and media files
class StaticStorage(S3Boto3Storage):
location = STATICFILES_LOCATION
class MediaStorage(S3Boto3Storage):
location = MEDIAFILES_LOCATION
file_overwrite = False
# Configure static and media files storage
STATICFILES_STORAGE = 'your_app_name.settings.StaticStorage'
DEFAULT_FILE_STORAGE = 'your_app_name.settings.MediaStorage'
# Set static and media URLs
STATIC_URL = f'https://{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com/{STATICFILES_LOCATION}/'
MEDIA_URL = f'https://{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com/{MEDIAFILES_LOCATION}/'
- Make sure your S3 bucket is configured properly with appropriate permissions for accessing and uploading files.
- Update your Django project’s
urls.py
file to serve static and media files during development:
# urls.py
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
]
# Serve static and media files during development
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Run Django’s collectstatic
management command to upload your static files to S3
python manage.py collectstatic
That’s it! Your Django application should now be configured to store static and media files on Amazon S3. Make sure to replace 'your-access-key-id'
, 'your-secret-access-key'
, 'your-bucket-name'
, and 'your-region-name'
with your actual AWS credentials and bucket information. Additionally, replace 'your_app_name'
with the name of your Django application.