解决django的template中如果无法引用MEDIA_URL问题
配置如下
TEMPLATES=[
下面
'context_processors':[
中添加
'django.core.context_processors.media',
会把MEDIA_URL配置在template中
这样在template下面就可以引用MEDIA_URL了
补充知识:在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上传路径
fromdjango.views.staticimportserve
fromMxOnline.settingsimportMEDIA_ROOT
配置url固定的里面的内容不能改的
url(r'media/(?P
.*)$',serve,{'document_root':MEDIA_ROOT}),
以上这篇解决django的template中如果无法引用MEDIA_URL问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。