如果在url中没有配置media,即使在settings设置了MEDIA_ROOT,也无法正常显示图片。
会遇到如下错误
Using the URLconf defined in me_blog.urls, Django tried these URL patterns, in this order:
blog/
admin/
The current path, media/banner/发货-2.jpg, didn‘t match any of these.
如何解决呢?需要一次做出如下操作:
1.正确配置MEDIA_URL和MEDIA_ROOT
settings中配置。
MEDIA_URL = ‘/media/‘ # 设置上传文件的路径 MEDIA_ROOT = os.path.join(BASE_DIR, ‘media‘) # 指定根目录
2.在Model中应用配置
class ProductInfo(models.Model):
# 商品模型:pic为该商品的图片在项目中存储的相对路径
pic = models.ImageField(verbose_name="图片路径", default="image/default.png", upload_to=‘df_goods/image/%Y/%m‘, null=True, blank=True) # 商品图片
3.配置url路由
from django.views.static import serve # 上传文件处理函数
from .settings import MEDIA_ROOT # 从配置中导入MEDIA_ROOT
urlpatterns = [
url(r‘^media/(?P<path>.*)$‘, serve, {"document_root":MEDIA_ROOT})
]
4.配置templates模板
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上传文件路径注册到模板中
],
},
},
]
5.在页面中使用
<img src="{{ MEDIA_URL }}{{ product.pic }}"> 其中{{ product.pic }}为商品的路径
页面经过渲染之后,在浏览器中会显示为:
<img src="/media/product/image/2019/05/product_detail.jpg">
原文:https://www.cnblogs.com/saptechnique/p/13213182.html