Install Required Packages:
Install django-storages package, which provides support for various storage backends including Amazon S3.
You can install it via pip:
pip install django-storages
Configure Django Settings:
Update your Django settings to use S3 for static and media files storage. Modify your settings.py file as follows:
# settings.py
# Import necessary modules
import os
# Configure static files storage using S3
AWS_STORAGE_BUCKET_NAME = 'your-bucket-name'
AWS_ACCESS_KEY_ID = 'your-access-key-id'
AWS_SECRET_ACCESS_KEY = 'your-secret-access-key'
AWS_S3_REGION_NAME = 'your-region-name'
AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com'
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/static/'
# Configure media files storage using S3
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/media/'
# Configure static and media directories
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Replace 'your-bucket-name', 'your-access-key-id', 'your-secret-access-key', and 'your-region-name' with your actual S3 bucket details.
Migrate Static and Media Files to S3:
Run Django management commands to collect static files and move media files to S3:
python manage.py collectstatic
python manage.py migrate
This will collect all static files from your Django apps and move them to the S3 bucket configured in your settings.
Test the Setup:
Test your Django application to ensure that static and media files are being served from S3. You can upload files through your Django admin or any file upload forms in your application to verify that media files are stored in S3.
Comments