Djangoroidの奮闘記

python,django,angularJS1~三十路過ぎたプログラマーの奮闘記

Django AmazonS3 Heroku でデプロイした時の話 後編

後編

後編では、media_url, static_url などを再設定していく

参照サイト

以下の2つを中心に進めていきます。

デフォルトの設定を確認する。

  <img src="{{ user.avatar.url }}">

上記のように記載すると、settings.pyのmedia_rootへ参照されるようになる。

    MEDIA_ROOT = '/var/media/'
    MEDIA_URL = 'http://media.example.com/'

goalは、ここのメディアルートを、s3にすること!

custom storage class を作成する。for our static file storage

保存場所はよく分からないけど、settingsから呼び出しやすいように、settings/custom_storages.pyに置いてある。(もしかしたら、rootの方がいいのかも。)

    # custom_storages.py
    from django.conf import settings
    from storages.backends.s3boto import S3BotoStorage

    class StaticStorage(S3BotoStorage):
        location = settings.STATICFILES_LOCATION

settings/production.pyにセットする。

 AWS_S3_CUSTOM_DOMAIN = '*******.s3-website-ap-northeast-1.amazonaws.com'

    STATIC_ROOT = 'staticfiles'

    STATICFILES_DIRS = (
        os.path.join(BASE_DIR, "static_in_pro", "our_static"),
    )

    STATICFILES_LOCATION = 'static'
    STATICFILES_STORAGE = 'custom_storages.StaticStorage'
    STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION)

こんな感じで、セットしてみる。

またerror! custom_storagesが見当たらないとのこと。

settingsフォルダと同じ階層ににファイルをセットしてみる。さらにmediarootも加えてみる。

production.py

    AWS_S3_CUSTOM_DOMAIN = "designtoollab.s3-website-ap-northeast-1.amazonaws.com"
    STATIC_ROOT = 'staticfiles'
    STATICFILES_DIRS = (
        os.path.join(BASE_DIR, "static_in_pro", "our_static"),
    )
    STATICFILES_LOCATION = 'static'
    STATICFILES_STORAGE = 'ecommerce2.custom_storages.StaticStorage'
    STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION)

    MEDIA_ROOT = 'mediafiles'
    MEDIAFILES_LOCATION = 'media'
    MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION)
    DEFAULT_FILE_STORAGE = 'ecommerce2.custom_storages.MediaStorage'

custom_strages.py

from django.conf import settings
from storages.backends.s3boto import S3BotoStorage

class StaticStorage(S3BotoStorage):
    location = 'static'

class MediaStorage(S3BotoStorage):
    location = 'media'

これで通った!しかし、どうも読み込みerrorが出ているし、異様に読み込みが遅いので、なんらかのerrorが出ていると思われる。

また後で考察することにする。