這篇文章主要介紹了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', ], }, }, ]
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')
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
以上是使用Django實作自訂404,500頁面的方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!