Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serve static files on heroku using AWS S3 for django?

i'm deploying a django application using heroku and AWS S3 for static files, the problem is that i haven't found information on how to link the Postgres DB of heroku with the S3 service.

I've already set the AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, S3_BUCKET, Add CORS Configuration, but my question is how can i link the S3 storage with the postgres DB of Heroku? Is this possible?

This is how my model looks in the admin, but if i upload the images here, after 5 minutes disappears. Image Upload for the model http://ishopss.com/imageUpload.png

Of course i can use static urls like this, but the problem is that i want to display different images for very course, not the same image for all. serve in the db http://ishopss.com/for.png

So my code needs to be like this, to serve different images aws static file http://ishopss.com/course.png

I hope some one could help me, Thanks.

like image 717
unixeO Avatar asked Dec 09 '13 21:12

unixeO


2 Answers

I found the solution in this posts:

http://blog.doismellburning.co.uk/2012/06/25/django-and-static-files/

http://offbytwo.com/2012/01/18/deploying-django-to-heroku.html

https://devcenter.heroku.com/articles/s3

Basically i need to download boto (pip install boto) and put it in requirements.txt(pip freeze > requirements.txt), and in settings.py add:

INSTALLED_APPS = ('storages',)

AWS_ACCESS_KEY_ID = 'xxxxxx'
AWS_SECRET_ACCESS_KEY = 'xxxxxxx'
AWS_STORAGE_BUCKET_NAME = 'bucket_name'


STATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'

STATIC_URL = 'http://s3.amazonaws.com/%s' % AWS_STORAGE_BUCKET_NAME + '/'

Then you need to set 'AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY', 'AWS_STORAGE_BUCKET_NAME'

using

$ heroku config:set AWS_ACCESS_KEY_ID=xxx AWS_SECRET_ACCESS_KEY=yyy
$ heroku config:set S3_BUCKET_NAME=appname-assets

Update the src and href in your html:

url http://ishopss.com/url.png

Finally you need to update the permissions in https://console.aws.amazon.com/

like image 167
unixeO Avatar answered Sep 29 '22 21:09

unixeO


Please take a look here:

  • http://blog.doismellburning.co.uk/2012/07/14/using-amazon-s3-to-host-your-django-static-files/
  • http://django-storages.readthedocs.org/en/latest/backends/amazon-S3.html

May be it will simplest way for you. I suppse {{ course.image }} will work from scratch. If not - you could create CDN point on AWS, and store CDN url in your django settings file. After that you html should look like:

{{ settings.CDN_URL }}/{{ course.image }}

If you like sugar, and hav some time you could write your own templatetags, which will do like :

{% my_static course,.image %} 
like image 37
Rustem Avatar answered Sep 29 '22 20:09

Rustem