解决django的template中如果无法引用MEDIA_URL问题

Ann ·
更新时间:2024-09-20
· 958 次阅读

配置如下

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

以上这篇解决django的template中如果无法引用MEDIA_URL问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持软件开发网。

您可能感兴趣的文章:解决django FileFIELD的编码问题django中url映射规则和服务端响应顺序的实现django3.02模板中的超链接配置实例代码



media 如果 Django url

需要 登录 后方可回复, 如果你还没有账号请 注册新账号