Django實現(xiàn)自定義404,500頁面教程
1.創(chuàng)建一個項目
django-admin.py startproject HelloWorld
2.進入HelloWorld項目,在manage.py的同一級目錄,創(chuàng)建templates目錄,并在templates目錄下新建404.html,500.html兩個文件。
3.修改settings.py
(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內(nèi)容,如果出錯則顯示500.html內(nèi)容。
相關(guān)文章
詳解如何用Flask中的Blueprints構(gòu)建大型Web應(yīng)用
Blueprints是Flask中的一種模式,用于將應(yīng)用程序分解為可重用的模塊,這篇文章主要為大家詳細介紹了如何使用Blueprints構(gòu)建大型Web應(yīng)用,需要的可以參考下2024-03-03Python抓取移動App數(shù)據(jù)使用mitmweb監(jiān)聽請求與響應(yīng)
這篇文章主要介紹了Python抓取移動App數(shù)據(jù)使用mitmweb監(jiān)聽請求與響應(yīng),mitmproxy控制臺方式、mitmdump與Python對接的方式、mitmweb可視化方式,需要的朋友可以參考一下2022-01-01