Django 設定media static

weixin_34293059發表於2017-11-25

Django 設定media static

本文python版本3.6.1,Django版本1.11.1

1、settings.py配置

增加django.template.context_processors.media

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')]
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'django.template.context_processors.media',
            ],
        },
    },
]

增加MEDIA_URL、MEDIA_ROOT

1
2
3
MEDIA_URL = '/media/'
 
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

2、urls.py

1
2
3
4
5
from east_web.settings import MEDIA_ROOT
from django.views.static import serve
 
# 配置上傳檔案的訪問處理函式
    url(r'^media/(?P<path>.*)$',  serve, {"document_root": MEDIA_ROOT}),

3、models.py使用

1
image = models.ImageField(max_length=100, upload_to="image/%Y/%m", default=u"image/default.png", verbose_name=u'頭像')

4、xadmin後臺頁面展示

5、media目錄

 

 

相關文章