AWS S3 bucket storage in a Django

mrcaption49

Pranav Bakare

Posted on September 12, 2024

AWS S3 bucket storage in a Django

To configure AWS S3 bucket storage in a Django project, you need to use the boto3 library and Django's storages module. Here's a step-by-step guide:

Step 1: Install the Required Packages

Install the boto3 and django-storages packages.

pip install boto3 django-storages
Enter fullscreen mode Exit fullscreen mode

Step 2: Update Django Settings

In your settings.py file, configure Django to use S3 for file storage.

  1. Add storages to INSTALLED_APPS:
INSTALLED_APPS = [
    ...
    'storages',
]

Enter fullscreen mode Exit fullscreen mode
  1. Add AWS S3 Bucket Configuration:
# AWS S3 Bucket Configurations
AWS_ACCESS_KEY_ID = 'your_aws_access_key'
AWS_SECRET_ACCESS_KEY = 'your_aws_secret_key'
AWS_STORAGE_BUCKET_NAME = 'your_bucket_name'
AWS_S3_REGION_NAME = 'your_region'  # e.g., 'us-west-1'

# S3 static and media file settings
AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com'

# Static files configuration (optional if you want to store static files on S3)
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/static/'

# Media files configuration
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/media/'
Enter fullscreen mode Exit fullscreen mode

Make sure to replace your_aws_access_key, your_aws_secret_key, your_bucket_name, and your_region with your actual AWS credentials and S3 bucket details.

Step 3: Create S3 Bucket and Set Permissions

  1. Create the S3 bucket in your AWS Console.

  2. Set appropriate bucket permissions to allow access to static and media files.

You can add the following bucket policy to grant public read access:


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

Enter fullscreen mode Exit fullscreen mode

Step 4: Collect Static Files

If you're using S3 for static files, run the following command to collect all static files and upload them to S3:


python manage.py collectstatic

Enter fullscreen mode Exit fullscreen mode

Now, your Django project is configured to use AWS S3 for storing media (and static, if configured) files.

Step 5: Testing

You can test by uploading media files through your Django application and confirming they are being stored in the S3 bucket. You should be able to access them via the URLs defined in your MEDIA_URL.

💖 💪 🙅 🚩
mrcaption49
Pranav Bakare

Posted on September 12, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

AWS S3 bucket storage in a Django
aws AWS S3 bucket storage in a Django

September 12, 2024