解決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上傳路徑
from django.views.static import servefrom MxOnline.settings import MEDIA_ROOT
配置url 固定的 里面的內容不能改的
url(r’media/(?P<path>.*)$’, serve, {’document_root’: MEDIA_ROOT}),
以上這篇解決django的template中如果無法引用MEDIA_URL問題就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章:
