Using Django’s ImageField with S3Storage
I wanted to add a django ImageField to a project I’m working on and have that upload to Amazon’s S3. It is relatively easy to do thanks to the storage type on the field. As a matter of fact it is as simple as this: http://blog.dev360.com/category/django/
The gotcha here is that the S3Storage component takes a bit more setup to get it right and working with the ImageField.
There are many ways to setup your AWS settings but a simple way is to just add them to your settings.py:
#S3 and S3 Storage settings #DEFAULT_FILE_STORAGE = 'S3Storage.S3Storage' AWS_ACCESS_KEY_ID = 'yourkeyid' AWS_SECRET_ACCESS_KEY = 'yoursecretacckey' AWS_STORAGE_BUCKET_NAME = 'yourbucketname' #probably easiest to create with S3fox plugin from S3 import CallingFormat AWS_CALLING_FORMAT = CallingFormat.SUBDOMAIN
You don’t need to change your DEFAULT_FILE_STORAGE unless you want to change where everything gets stored by default (umm..yeah). In our case we are looking to change just this one field on one of our models so we will set the storage like the article at blog.dev360.com above does:
class YourClass(models.Model):
storage = S3Storage()
file = models.ImageField(upload_to=your_upload_func, storage = storage)
That is literally just about it, but there are a couple of other things that might hang you up…mainly make sure you understand that you have a default bucket that you must create before you can upload (S3Fox, or use the command line) and whatever path you pass into the upload_to argument will be appended to the bucket. So you will be uploading to:
/yourbucketname/yourpath/
Hope that helps.
Add New Comment
Viewing 3 Comments
Thanks. Your comment is awaiting approval by a moderator.
Do you already have an account? Log in and claim this comment.
Do you already have an account? Log in and claim this comment.
Do you already have an account? Log in and claim this comment.
Do you already have an account? Log in and claim this comment.
Add New Comment