首頁  >  文章  >  後端開發  >  使用Django實作自訂404,500頁面的方法

使用Django實作自訂404,500頁面的方法

高洛峰
高洛峰原創
2017-03-28 09:32:292408瀏覽

這篇文章主要介紹了Django實作自訂404,500頁面的詳細方法,非常簡單實用,有需要的小夥伴可以參考下

1.建立一個專案

#django-admin.py startproject HelloWorld

# 2.進入HelloWorld專案,在manage.py的相同等級目錄,建立templates目錄,並在templates目錄下新建404.html,500.html兩個檔案。

#(1.)DEBUG修改為False,(2.)ALLOWED_HOSTS新增指定網域或IP,(3.)指定範本路徑'DIRS' : [os.path.join(BASE_DIR,'templates')],

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['localhost','www.example.com', '127.0.0.1']
TEMPLATES = [
 {
  'BACKEND': 'django.template.backends.django.DjangoTemplates',
  'DIRS': [os.path.join(BASE_DIR, 'templates')],
  'APP_DIRS': True,
  'OPTIONS': {
   'context_processors': [
    'django.template.context_processors.debug',
    'django.template.context_processors.request',
    'django.contrib.auth.context_processors.auth',
    'django.contrib.messages.context_processors.messages',
   ],
  },
 },
]
4.新建一個views.py

from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def hello(request):
 return HttpResponse('Hello World!')
@csrf_exempt
def page_not_found(request):
 return render_to_response('404.html')
@csrf_exempt
def page_error(request):
 return render_to_response('500.html')
5.修改urls.py,程式碼如下

from django.conf.urls import url
from django.contrib import admin
import HelloWorld.views as view
urlpatterns = [
 url(r'^admin/', admin.site.urls),
 url(r'^test$', view.hello),
]
handler404 = view.page_not_found
handler500 = view.page_error
重新編譯,重啟uwsgi,輸入localhost/HelloWorld/test,顯示'Hello World!',輸入其它位址會顯示404.html內容,如果出錯則顯示500.html內容。

以上是使用Django實作自訂404,500頁面的方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn