Django中MEDIA_ROOT和MEDIA_URL

在django上传图片前端使用动态的配置方法

MEDIA_ROOT 代表着 要上传的路径会和你在models中写的上传的路径进行拼节形成最终文件上传的路径 
MEDIA_URL主要就是映射了 在前端使用media_url 当你的media_root 发生改变的时候不用去更改前端模板中的内容

要想正常的显示图片 还需要下面几步:
1
在settings 中配置路径
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media' )
2
在TEMPLATES 中添加一个上下文环境 'django.core.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.core.context_processors.media',
             ],
         },
     },
3
在url中配置media请求的url
首先需要导入下面的库 和在settings 中配置的 MEDIA_ROOT上传路径
from django.views. static import serve
from MxOnline.settings import MEDIA_ROOT
 
配置url  固定的 里面的内容不能改的
url(r 'media/(?P<path>.*)$' , serve, { 'document_root' : MEDIA_ROOT}),
</code>

猜你喜欢

转载自www.cnblogs.com/icat-510/p/9034727.html