0

I wanna deploy Django project on AWS EC2. For my media files, I need a bucket on S3. My project working good on localhost, and I can access media from S3, but after deploying I can't get AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY that's why I'm getting Server Error 500.

This is the main part of settings.py

DEBUG = False
ALLOWED_HOSTS = ['XXXXXXXX']
INSTALLED_APPS = [
    'apps.comic',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'storages',
]
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'apps/comic/static/media')
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')

AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY')
AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME')

AWS_S3_FILE_OVERWRITE = False
AWS_DEFAULT_ACL = None

DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'

I tried to make ~/.aws/credentials:

[default]
aws_access_key_id = X...X
aws_secret_access_key = X...X

But it's the same result Server Error 500. I can get just login/registration page because I don't have any media files on it.

What should I do for getting media files after production? Do I need to make some changes in credentials or in settings.py file?

Mary Brykina
  • 71
  • 1
  • 5

1 Answers1

0

Your problem is because of those three lines:

AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY')
AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME')

specifically this part os.environ.get it basically instructs your python script to search for your AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY in operating system variables.

To solve this you have two options:

  • Add AWS variables to EC2 environ variables by running this on your terminal export AWS_KEY=Your_Key

OR

  • Write your ID and Key directly to your settings.py file

     AWS_ACCESS_KEY_ID = "key_string_here"
     AWS_SECRET_ACCESS_KEY = "secret_string_here"
     AWS_STORAGE_BUCKET_NAME = "bucket_name_here"
    

I would prefer the second option as it's more portable.

Ramy M. Mousa
  • 5,727
  • 3
  • 34
  • 45