一、問題
在構建網站的時候我們會用到全局的templates處理錯誤的網頁,此時我們需要對urls進行一個映射,使得在使用的時候避免重復調用。在使用的時候還會產生錯誤代碼:
第一個是404界面的,第二個是500界面的(Django:2.2.2)
?: (urls.E007) The custom handler404 view 'index.views.page_not_found' does not take the correct number of arguments (request, exception). ?: (urls.E007) The custom handler500 view 'index.views.page_error' does not take the correct number of arguments (request).
全局視圖
二、解決
在一個views中關聯html,然后再將views和url建立隱射關系。注意:解決兩個問題的關鍵在於在Django2.2.2下,404的錯誤不能有參數:exception,但是500的錯誤必須有exception,如此解決問題。
1.關聯views
隨便選擇一個app的views添加如下的代碼
from django.shortcuts import render # 404
def page_error(request): return render(request, 'error404.html', status=404) # 500
def page_not_found(request, exception): return render(request, 'error404.html', status=500)
2.映射
在項目的url中使用handler404和handler500這兩個指定的變量來完成數據的映射關系,因為是從index的APP中導入的因此是【from index import views】。
# 設置404、500錯誤狀態碼
from index import views handler404 = views.page_not_found handler500 = views.page_error
3.HTML的代碼
其中用{% load staticfiles %}加載全局的資源;用{% static 'images\pk_1.jpg' %}進行資源調用;用href='/music/comment'完成主界面的跳轉
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>頁面沒找到</title> {% load staticfiles %} </head>
<body>
<img src="{% static 'images\pk_1.jpg' %}" width="400" height="400">
<br>
<div class="error_main"><a href='/music/comment' class="index">回到首頁</a></div>
</body>
</html>
4.設置
最后將setting中的debug改成False就可以觀察到結果了。
三、結果展示
四、總結
報錯信息是由於缺少參數,有時候圖片加載有問題,分別刷新一下debug的設置,數據就可以顯示出來。
附上Django的參考文檔:
https://docs.djangoproject.com/en/2.1/ref/settings/#databases