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 导入模块和解决文件句柄找不到问题

如果你退出 Python 解释器并重新进入,你做的任何定义(变量和方法)都会丢失。因此,如果你想要编写一些更大的程序,为准备解释器输入使用一个文本编辑器会更好,并以那个文件替代作为输入执...

python mysqldb连接数据库

没办法就下了一个2.6,如果用2.4就太低了,又折腾了,半天找到了MySQL-python-1.2.2.win32-py2.6.exe 这个安装文件,安装完成,执行 import MyS...

python实现从wind导入数据

从wind导入到的数据的格式是instance。 如下载一系列资产在某一段时间的收盘价格。 一系列资产保存在list里面,一并下载。 日期格式为“2018-02-28”。 一个数字串儿表...

解决安装tensorflow遇到无法卸载numpy 1.8.0rc1的问题

最近在关注 Deep Learning,就在自己的mac上安装google的开源框架Tensorflow 用 sudo pip install -U tensorflow 安装的时候总...

Python实现感知器模型、两层神经网络

Python实现感知器模型、两层神经网络

本文实例为大家分享了Python实现感知器模型、两层神经网络,供大家参考,具体内容如下 python 3.4 因为使用了 numpy 这里我们首先实现一个感知器模型来实现下面的对应关系...