python-爲Django項目上的每個應用程序創建不同的自定義404頁面

有沒有一種方法可以爲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參數.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章