django顯示圖片對新手來說真的算是一個坑。。
這里記錄下小白爬坑的歷程。
首先,你需要一個可以運行的django服務器,能顯示正常的html文本,無法顯示圖片
這是html的文本,可以顯示文字,無法顯示圖片
<h1>An Image Test</h1> <img src="medias/1.jpg">
首先,在網上搜到的辦法,搜到了幾個復雜的設置方法,結果都失敗了。
有一個類較為簡單,可以試一試
大概是這樣的:
在 django 中不像PHP那樣有根目錄的概念 而取而代之的是包的概念, 通過URLS.PY 來提供每個URL 對應的DJANGO的 函數來顯示頁面
在包的 temolates目錄中 的html頁面里面 是不能直接寫圖片 或者 CSS JS 文件的 相對|絕對 路徑的 , 而是用 URLS 提供的URL對應 圖片/js/css 目錄的
調用方法如下:
url(r'^medias/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '/web/www/python/templates/images'}),
r'^medias/(?P<path>.*)$' # 是要 展示url的 方法/文件名 {'document_root':'/web/www/python/templates/images'} # 是要 提供 圖片目錄的真實路徑
這樣 就能用 <img src="/medias/images.gif" /> 調用 圖片了
一切都完成了,結果報錯???
(r'^medias/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '/web/www/python/templates/images'}), 中django報錯
說是'django.views.static.serve'調用有問題,
改成url(r'^medias/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '/web/www/python/templates/images'}),也有問題,出現 TypeError: view must be a callable or a list/tuple in the case of include().
后來發現(r'^medias/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '/web/www/python/templates/images'})估計是老版本django的調用方法,在新版本djago中改用url(“”,)來調用,將'django.views.static.serve' 改成import的方式:
from django.views.static import serve url(r'^medias/(?P<path>.*)$', serve, {'document_root': '真實文件的目錄/static/images'}),
打開瀏覽器
直接訪問圖片地址:
也沒問題,大功告成,哈哈