一、settings配置
1. 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’,
‘blog.views.global_setting’,
‘django.template.context_processors.media’,这句一定要有,否则图片无法显示
],
},
},
]
2.配置路径
MEDIA_URL = ‘/uploads/’
MEDIA_ROOT = os.path.join(BASE_DIR, ‘uploads’)
uuploads即上传图片的路径
二、URL配置
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^admin/uploads/(?P<dir_name>[^/]+)$',upload_image, name='upload_image' ),
path('', index, name='index '),
path('uploads/(?P<path>.*)', serve, {'document_root':settings.MEDIA_ROOT}),
#捕获achive页面的url
path('achive/', achive, name='achive')
]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)配置静态路径很关键,否则无法显示
三、前端
{% for adver in adver_list%}
<img src="{{ MEDIA_URL }}{{ adver.imag }}">
{% endfor %}