解决django的template中如果无法引用MEDIA_URL问题
作者:天马行空波 时间:2023-06-12 15:09:07
配置如下
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上传路径
from django.views.static import serve
from MxOnline.settings import MEDIA_ROOT
配置url 固定的 里面的内容不能改的
url(r'media/(?P<path>.*)$', serve, {'document_root': MEDIA_ROOT}),
来源:https://blog.csdn.net/jiangbo721/article/details/78515496
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Javascript简单实现面向对象编程继承实例代码
python实现在IDLE中输入多行的方法
vue之计算属性的缓存computed的用法解读
![](https://img.aspxhome.com/file/2023/5/126525_0s.png)
javascript面向对象技术基础(三)
JavaScript性能优化--创建文档碎片
使用Python实现将list中的每一项的首字母大写
关于Pyinstaller闪退的补救措施
![](https://img.aspxhome.com/file/2023/5/80635_0s.jpg)
Python matplotlib seaborn绘图教程详解
![](https://img.aspxhome.com/file/2023/6/109866_0s.png)
详解如何用Python写个听小说的爬虫
![](https://img.aspxhome.com/file/2023/5/127635_0s.png)
Python设计模式结构型享元模式
![](https://img.aspxhome.com/file/2023/4/115664_0s.png)
详解微信小程序中的页面代码中的模板的封装
Linux下修改MySQL编码的方法
![](https://img.aspxhome.com/file/2023/2/112892_0s.jpg)
python 网络编程详解及简单实例
带你轻松接触MySQL数据库的出错代码列表
Python编写条件分支代码方法
.Net Core微服务网关Ocelot基础介绍及集成
![](https://img.aspxhome.com/file/2023/6/126206_0s.jpg)
使用python实现抓取中国银行外汇牌价首页数据实现
![](https://img.aspxhome.com/file/2023/9/128749_0s.jpg)
prototype.js1.4版开发者手册
![](https://img.aspxhome.com/file/UploadPic/up/2007093019082399.jpg)
Golang实现断点续传功能
![](https://img.aspxhome.com/file/2023/8/99058_0s.jpg)