1.settings.py配置static文件和图片的路径:
DEBUG = False
STATIC_ROOT = 'E:\drf_admin-master\static'
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "E:\\drf_admin-master\\frontend\\dist\\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': ['E:\\drf_admin-master\\frontend\\dist\\'],
'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
from django.views.static import serve
# admin管理页面
path('admin/', admin.site.urls),
path('', TemplateView.as_view(template_name="index.html")),
url(r'^media/(?P<path>.*)$',serve,{'document_root':settings.MEDIA_ROOT}),
url(r'^static/(?P<path>.*)$',serve,{'document_root':settings.STATIC_ROOT}),
|