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学生成绩管理系统简洁版

讲起学生成绩管理系统,从大一C语言的课程设计开始,到大二的C++课程设计都是这个题,最近在学树莓派,好像树莓派常用Python编程,于是学了一波Python,看了一点基本的语法想写点东西...

Python使用requests提交HTTP表单的方法

Python的requests库, 其口号是HTTP for humans,堪称最好用的HTTP库。 使用requests库,可以使用数行代码实现自动化的http操作。以http pos...

Python进度条的制作代码实例

这篇文章主要介绍了Python进度条的制作代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 import sys,time...

python获取当前用户的主目录路径方法(推荐)

Python获取当前用户的主目录路径, 示例代码如下: #! /usr/bin/python # -*- coding: utf-8 -*- import os print os...

pygame学习笔记(5):游戏精灵

pygame学习笔记(5):游戏精灵

据说在任天堂FC时代,精灵的作用相当巨大,可是那时候只知道怎么玩超级玛丽、魂斗罗,却对精灵一点也不知。pygame.sprite.Sprite就是Pygame里面用来实现精灵的一个类,使...