解決django的template中如果無法引用MEDIA_URL問題
配置如下
TEMPLATES = [
下面
’context_processors’: [
中添加
’django.core.context_processors.media’,
會把MEDIA_URL 配置在template中
這樣在template下面 就可以引用MEDIA_URL了
補充知識:在django中使用 MEDIA_URL 和 MEDIA_ROOT
在django上傳圖片前端使用動態(tài)的配置方法
MEDIA_ROOT 代表著 要上傳的路徑會和你在models中寫的上傳的路徑進行拼節(jié)形成最終文件上傳的路徑
MEDIA_URL主要就是映射了 在前端使用media_url當你的media_root發(fā)生改變的時候不用去更改前端模板中的內(nèi)容
前端模板中的寫法
后面是從數(shù)據(jù)庫中 查詢出來的 上傳文件的地址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 中添加一個上下文環(huán)境 ’django.core.context_processors.media’, 這個會
自動的把MEDIA_URL 注冊到前端的模板中的 沒有這個上下文環(huán)境 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 固定的 里面的內(nèi)容不能改的
url(r’media/(?P<path>.*)$’, serve, {’document_root’: MEDIA_ROOT}),
以上這篇解決django的template中如果無法引用MEDIA_URL問題就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。
相關文章:
1. ajax請求添加自定義header參數(shù)代碼2. Gitlab CI-CD自動化部署SpringBoot項目的方法步驟3. 基于javascript處理二進制圖片流過程詳解4. 教你如何寫出可維護的JS代碼5. ASP中解決“對象關閉時,不允許操作。”的詭異問題……6. Django-migrate報錯問題解決方案7. ASP刪除img標簽的style屬性只保留src的正則函數(shù)8. 使用Python和百度語音識別生成視頻字幕的實現(xiàn)9. idea刪除項目的操作方法10. 怎樣才能用js生成xmldom對象,并且在firefox中也實現(xiàn)xml數(shù)據(jù)島?
