Django——靜態檔案本地處理以及400,500頁面配置
阿新 • • 發佈:2018-12-14
Django中對靜態檔案的儲存主要在media與static兩個目錄下,media放使用者與應用相關的檔案,static放js等與程式相關與使用者沒有直接關聯的檔案。
在setting中配置的檔案相關常見變數
- STATIC_ROOT static檔案目錄地址路徑,在執行collectstatic時靜態檔案統一收集到此路徑下 - STATIC_URL static檔案網路路徑 - STATICFILES_DIRS 公共靜態檔案目錄 - STATICFILES_STORAGE - STATICFILES_FINDERS - MEDIA_ROOT MEDIA檔案目錄地址路徑 - MEDIA_URL MEDIA檔案目錄網路路徑
使用靜態檔案
- 在自定義的staticfiles_dirs中尋找靜態檔案
- 保證 django.contrib.staticfiles 在 INSTALLED_APPS 中.
- 在 TEMPLATES 配置中新增 django.template.context_processors.static
- 在模板中使用 STATIC_URL 變數,eg:<img src="{{STATIC_URL}}girl.png>
- 在自定義static_root中尋找
if settings.DEBUG:
urlpatterns += [
url(r'^static/(?P<path>.*)$', views.serve),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
方式一隻在開發環境下有用
404 500 頁面配置
setting檔案配置templates dir路徑
template目錄下設計對應錯誤頁面
views檔案編寫相應view函式
def page_not_found(request):
return render_to_response( 'user/404.html', status=404)
def page_error(request):
return render_to_response('user/500.html', status=500)
urls中為404 500控制代碼指定處理函式
handler404 = page_not_found
handler500 = page_error