在django中使用 MEDIA_URL 和 MEDIA_ROOT

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

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

前端模板中的写法
后面是从数据库中 查询出来的 上传文件的地址url
"{{ MEDIA_URL }}{{ course_org.image }}"
前端生成的路径
"/media/org/2017/07/qhdx-logo.png"/

要想正常的显示图片 还需要下面几步:


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}),



发布了54 篇原创文章 · 获赞 7 · 访问量 3万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章