Pranav Bakare
Posted on October 14, 2024
If you want your Django application to store images (or other media files) in an Amazon S3 bucket, follow the detailed steps below to integrate and deploy your Django project on Render while ensuring seamless S3 storage for media files.
Step 1: Prepare Your Django Project for Deployment
1.1 Ensure All Dependencies are Listed
Create a requirements.txt file that includes all your project dependencies:
pip freeze > requirements.txt
Make sure to include these additional packages:
boto3: AWS SDK for Python, to interact with S3.
django-storages: To integrate Django with AWS S3.
pip install boto3 django-storages
1.2 Create a Procfile
Create a Procfile in the root of your project to specify how to run the application:
web: gunicorn myproject.wsgi:application
Replace myproject with the name of your Django project.
1.3 Configure Media Files to Use Amazon S3
Update your settings.py to include the following configuration:
settings.py
INSTALLED_APPS += ['storages']
AWS S3 Configuration
AWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY')
AWS_STORAGE_BUCKET_NAME = os.getenv('AWS_STORAGE_BUCKET_NAME')
AWS_S3_REGION_NAME = os.getenv('AWS_S3_REGION_NAME')
AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com'
Media files (images, etc.) will be stored on S3
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/media/'
Optional: Configure static files to be served from S3
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/static/'
Ensure boto3
and django-storages
are installed
This configuration ensures that any file uploaded via Django (e.g., user profile pictures, product images) will be stored directly on Amazon S3.
1.4 Configure Allowed Hosts
Add your Render service URL to ALLOWED_HOSTS in settings.py:
ALLOWED_HOSTS = ['your-django-backend-url.onrender.com']
1.5 Database Configuration
If using PostgreSQL provided by Render, update your database settings:
import dj_database_url
DATABASES = {
'default': dj_database_url.config(conn_max_age=600)
}
Ensure dj-database-url is listed in your requirements.txt.
1.6 Security Settings
Set up your production-ready settings:
DEBUG = False
Ensure secure settings like SECURE_SSL_REDIRECT, CSRF_COOKIE_SECURE, SESSION_COOKIE_SECURE are correctly configured.
Use environment variables for DJANGO_SECRET_KEY and other sensitive data.
Step 2: Create Render Configuration File
Create a render.yaml file:
services:
- type: web
name: my-django-app
env: python
buildCommand: pip install -r requirements.txt
startCommand: gunicorn myproject.wsgi:application
envVars:
- key: DATABASE_URL fromDatabase: name: my-database
- key: AWS_ACCESS_KEY_ID sync: false
- key: AWS_SECRET_ACCESS_KEY sync: false
- key: AWS_STORAGE_BUCKET_NAME sync: false
- key: AWS_S3_REGION_NAME sync: false
- key: DJANGO_SECRET_KEY sync: false
- key: ALLOWED_HOSTS value: 'your-django-backend-url.onrender.com'
Step 3: Set Up Amazon S3 Bucket
3.1 Create an S3 Bucket
Log in to your AWS Management Console.
Navigate to S3 and click Create bucket.
Set a unique bucket name (e.g., my-django-media-bucket).
Choose a region and configure permissions (make sure to allow read permissions for objects).
3.2 Create an IAM User for S3 Access
Go to IAM in the AWS console and create a new user.
Assign AmazonS3FullAccess or create a custom policy with the required permissions.
Generate access keys (you'll need these for AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY).
Step 4: Push Your Code to GitHub
4.1 Initialize Git and Push Code
git init
git add .
git commit -m "Initial commit for Render deployment"
git remote add origin https://github.com/yourusername/your-repo-name.git
git push -u origin master
Step 5: Deploy to Render
5.1 Create a New Web Service on Render
Go to Render’s dashboard, click New → Web Service.
Connect your GitHub repository.
5.2 Configure Service Settings
Select the branch to deploy (usually master or main).
Render will detect your render.yaml file and set up the service.
5.3 Set Up Environment Variables
Go to the Environment tab in the Render dashboard:
Add the following environment variables:
DATABASE_URL: Render will generate this if you created a PostgreSQL database.
AWS_ACCESS_KEY_ID: From your IAM user credentials.
AWS_SECRET_ACCESS_KEY: From your IAM user credentials.
AWS_STORAGE_BUCKET_NAME: Your S3 bucket name.
AWS_S3_REGION_NAME: The region your S3 bucket is in.
DJANGO_SECRET_KEY: A secure, random string.
ALLOWED_HOSTS: Your Render service URL.
Step 6: Running Migrations and Testing
6.1 Deploy the Service
Click Create Web Service. Render will build and deploy your Django application. Monitor the logs for any errors.
6.2 Post-Deployment: Run Database Migrations
After the service is deployed, log in to your Render service shell and run:
python manage.py migrate
6.3 Verify Media File Uploads
Test uploading images or media files through your Django application. Ensure they are correctly stored in the S3 bucket and accessible via the URLs.
Additional Notes:
CORS Configuration: Ensure your S3 bucket has the correct CORS configuration to allow access from your frontend.
File Permissions: Make sure uploaded files to S3 have public-read permissions (adjust S3 bucket policy if necessary).
Conclusion:
This detailed guide provides the necessary steps to deploy a Django application on Render, ensuring media files are seamlessly stored on Amazon S3. This setup improves scalability and offloads static/media file handling from your web server, making your application more efficient and production-ready.
Posted on October 14, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.