解決django的template中如果無法引用MEDIA_URL問題
配置如下
TEMPLATES = [
下面
’context_processors’: [
中添加
’django.core.context_processors.media’,
會把MEDIA_URL 配置在template中
這樣在template下面 就可以引用MEDIA_URL了
補(bǔ)充知識:在django中使用 MEDIA_URL 和 MEDIA_ROOT
在django上傳圖片前端使用動態(tài)的配置方法
MEDIA_ROOT 代表著 要上傳的路徑會和你在models中寫的上傳的路徑進(jìn)行拼節(jié)形成最終文件上傳的路徑
MEDIA_URL主要就是映射了 在前端使用media_url當(dāng)你的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
首先需要導(dǎo)入下面的庫 和在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)。
相關(guān)文章:
1. css代碼優(yōu)化的12個技巧2. .NET SkiaSharp 生成二維碼驗(yàn)證碼及指定區(qū)域截取方法實(shí)現(xiàn)3. jsp網(wǎng)頁實(shí)現(xiàn)貪吃蛇小游戲4. MyBatis JdbcType 與Oracle、MySql數(shù)據(jù)類型對應(yīng)關(guān)系說明5. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向6. 在JSP中使用formatNumber控制要顯示的小數(shù)位數(shù)方法7. 存儲于xml中需要的HTML轉(zhuǎn)義代碼8. ASP中實(shí)現(xiàn)字符部位類似.NET里String對象的PadLeft和PadRight函數(shù)9. ASP中if語句、select 、while循環(huán)的使用方法10. ASP基礎(chǔ)入門第八篇(ASP內(nèi)建對象Application和Session)
