1
在settings 中分别配置static文件和图片的路径
STATICFILES_DIRS = [os.path.join(BASE_DIR,'portfolio/static/'),]
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR,'static')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
2
在TEMPLATES 中添加一个上下文环境 ‘django.template.context_processors.media’, 这个会自动的把MEDIA_URL 注册到前端的模板中的 没有这个上下文环境MEDIA_URL在前端是没有显示的
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',
],
},
},
]
3
导入url模块
from django.conf.urls import url
url(r'^media/(?P<path>.*)$',serve,{'document_root':settings.MEDIA_ROOT})
url(r'^static/(?P<path>.*)$',serve,{'document_root':settings.STATIC_ROOT})
亲测有效,good!!!