Skip to content

Instantly share code, notes, and snippets.

@aaronromeo
Created May 3, 2014 13:07
Show Gist options
  • Save aaronromeo/5d9db93b7fdb58647859 to your computer and use it in GitHub Desktop.
Save aaronromeo/5d9db93b7fdb58647859 to your computer and use it in GitHub Desktop.
Storing images on S3 with Django

You'll need these libraries

  • pip install Pillow
  • pip install django-storages
  • pip install boto
import os
from django.db import models
def upload_avatar_to(obj, filename):
filename_base, filename_ext = os.path.splitext(filename)
s3filename = "profiles/{}{}{}".format(obj.first_name.lower(), obj.last_name.lower(), filename_ext.lower())
return s3filename
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
image = models.ImageField(blank=True, upload_to=upload_avatar_to)
def __unicode__(self):
return '{} {}'.format(self.first_name, self.last_name)
class Meta:
unique_together = ('first_name', 'last_name')
ordering = ['last_name', 'first_name']
INSTALLED_APPS = (
#...
'storages',
#...
)
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
AWS_S3_SECURE_URLS = False # use http instead of https
AWS_QUERYSTRING_AUTH = False # don't add complex authentication-related query parameters for requests
AWS_S3_ACCESS_KEY_ID = os.getenv('AWS_S3_ACCESS_KEY_ID') # enter your access key id
AWS_S3_SECRET_ACCESS_KEY = os.getenv('AWS_S3_SECRET_ACCESS_KEY') # enter your secret access key
AWS_STORAGE_BUCKET_NAME = 'yourbucketsname'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment