1. 程式人生 > 程式設計 >Django自定義全域性403、404、500錯誤頁面的示例程式碼

Django自定義全域性403、404、500錯誤頁面的示例程式碼

自定義模板

403

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>403-禁止訪問</title>
</head>
<body>
HTTP 403 - 禁止訪問
</body>
</html>

404

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>404-無法找到檔案</title>
</head>
<body>
HTTP 404- 無法找到檔案
</body>
</html>

500

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>500-伺服器錯誤</title>
</head>
<body>
HTTP 500 - 內部伺服器錯誤
</body>
</html>

編寫檢視

# 全域性403、404、500錯誤自定義頁面顯示
def page_not_found(request):
 return render(request,'404.html')


def page_error(request):
 return render(request,'500.html')


def permission_denied(request):
 return render(request,'403.html')

修改url

from .views import page_error,page_not_found,permission_denied


urlpatterns = [
 # ...
]

# 定義錯誤跳轉頁面
handler403 = permission_denied
handler404 = page_not_found
handler500 = page_error

嘗試使用無許可權使用者訪問,看是否會顯示該頁面

如果不對,修改settings.py中的DEBUG的值

DEBUG = False

注:若是DEBUG=True,有些情況下則不會生效

Http404丟擲異常

raise Http404('資源不存在<id:{}>,請訪問 xxx 檢視')

模板中捕獲異常資訊

使用{{ exception }}即可捕獲異常資訊,轉換為html程式碼{{ exception|safe }},可以根據這些程式碼中的id等,得到跳轉的連結,參考

<!DOCTYPE html>
{% load static %}
<html lang="en">
<style type="text/css">
 .pic {
  margin: auto;
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
 }
</style>
<head>
 <meta charset="UTF-8">
 <title>404-無法找到檔案</title>
 <link href="//cdn.bootcss.com/toastr.js/latest/css/toastr.min.css" rel="external nofollow" rel="stylesheet">
</head>
<body>
<a href="//blog.starmeow.cn" rel="external nofollow" ><img class="pic" src="{% static 'errors/404.gif' %}"></a>
<p hidden>{{ exception|safe }}</p>

<script src="//code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="//cdn.bootcss.com/toastr.js/latest/js/toastr.min.js"></script>
<script>

 toastr.options = { // toastr配置
  "closeButton": true,"debug": false,"progressBar": true,"positionClass": "toast-top-center","showDuration": "400","hideDuration": "1000","timeOut": "7000","extendedTimeOut": "1000","showEasing": "swing","hideEasing": "linear","showMethod": "fadeIn","hideMethod": "fadeOut"
 };

 $(function () {
  let redirect_url = $('#redirect_url').text();
  if (redirect_url.indexOf('//') === 0 || redirect_url.indexOf('http') === 0) { // 一連結開頭才跳轉
   toastr.warning('{{ exception|safe }}','跳轉中');
   setTimeout(function () {
    //這裡寫時間到後執行的程式碼
    $(location).attr('href',redirect_url);
   },3000);
  }
 })

</script>
</body>
</html>

後端

raise Http404('訪問資源不存在,即將跳轉 <span id="redirect_url">{}</span>'.format('blog.starmeow.cn'))
那麼當出現404錯誤是,jquery就獲取該di的值,如果是//或者是http開頭,表明可能是個連結(後端請限制格式),前端直接跳轉

到此這篇關於Django自定義全域性403、404、500錯誤頁面的示例程式碼的文章就介紹到這了,更多相關Django 403、404、500錯誤頁面內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!