Django实现自定义404,500页面教程

yipeiwu_com5年前Python基础

1.创建一个项目

django-admin.py startproject HelloWorld

2.进入HelloWorld项目,在manage.py的同一级目录,创建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内容,如果出错则显示500.html内容。

相关文章

基于python的Paxos算法实现

基于python的Paxos算法实现

理解一个算法最快,最深刻的做法,我觉着可能是自己手动实现,虽然项目中不用自己实现,有已经封装好的算法库,供我们调用,我觉着还是有必要自己亲自实践一下。 这里首先说明一下,python这种...

numpy排序与集合运算用法示例

numpy排序与集合运算用法示例

这里有numpy数组的相关介绍/post/130657.htm 排序 numpy与python列表内置的方法类似,也可通过sort方法进行排序。 用法如下: In [1]: imp...

python通过shutil实现快速文件复制的方法

本文实例讲述了python通过shutil实现快速文件复制的方法。分享给大家供大家参考。具体如下: python通过shutil实现快速文件拷贝,shutil使用起来非常方便,可以通过p...

对python GUI实现完美进度条的示例详解

对python GUI实现完美进度条的示例详解

在用python做一个GUI界面时,想搞一个进度条实时显示下载进度,但查阅很多博客,最后的显示效果都类似下面这种: 这种效果在CMD界面看着还可以,但放到图形界面时就有点丑了,所以我用...

python生成随机mac地址的方法

本文实例讲述了python生成随机mac地址的方法。分享给大家供大家参考。具体实现方法如下: #!/usr/bin/python import random def randomMA...