有沒有一種方法可以爲Django項目中的每個應用程序創建多個自定義錯誤模板,我的意思是,在我的項目中,我有3個應用程序,每個應用程序將顯示3種不同的custom 404錯誤.
現在,我在後臺應用程序和前臺顯示相同的404錯誤頁面.
最佳答案
創建一個自定義error view並將其分配給根urls.py中的handler404變量:
from django.views.defaults import page_not_found
def my_error_404(request, exception):
template_name = '404.html'
if request.path.startswith('/backoffice/'):
template_name='backoffice/404.html'
elif request.path.startswith('/frontoffice/'):
template_name='frontoffice/404.html'
return page_not_found(request, exception, template_name=template_name)
複製代碼
此代碼適用於Django 1.9.如果使用django< = 1.9,則從視圖中刪除exception參數.