Djangoのdeployに関する覚え書き - 其の二

MEDIA_URLの設定方法

(1) setting.pyに以下を追加。

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home2/media/media.lawrence.com/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, "media")

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
MEDIA_URL = '/MySystem_media/'


TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                ( ... 適切に記述 ... )
                'django.template.context_processors.media',
            ],
        },
    },
]

(2) プロジェクトトップのurls.pyに以下を記述。

from django.conf.urls.static import static
import django.contrib.staticfiles
import getpass

urlpatterns = [
   ( ... 適切に記述 ... )
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

if settings.DEBUG and getpass.getuser() != "www-data":
    urlpatterns += [
        url(r'^%s/(?P<path>.*)$' % settings.MEDIA_URL.strip('/'),
            django.contrib.staticfiles.views.serve),
    ]

(3) /etc/apache2/sites-enabled/000-default.confに以下を記述。

Alias /MySystem_media/ /home/taro/MyDjangoSystem/media/

<Directory /home/taro/MyDjangoSystem/media/>
Require all granted
</Directory>

※ URLの最初・最後のスラッシュ'/'の有無に十分注意。本サイトの記述は必ずしも正確ではない。