Django实现自定义404,500页面教程
作者:YoYong 时间:2021-06-20 06:23:07
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内容。
来源:http://www.yoyong.com/archives/987
标签:Django,自定义404


猜你喜欢
Python3 pandas 操作列表实例详解
2021-11-30 14:24:12
利用ThinkPHP内置的ThinkAjax实现异步传输技术的实现方法
2023-09-11 15:11:50
vue使用iframe嵌入网页的示例代码
2024-05-05 09:12:04
Sublime Text3最新激活注册码分享适用2020最新版 亲测可用
2023-02-03 07:18:38

使IE浏览器支持PNG格式图片的透明效果
2008-02-02 16:20:00

javascript在事件监听方面的兼容性小结
2024-04-29 13:45:19
批量更新数据库所有表中字段的内容,中木马后的急救处理
2024-01-27 21:19:54
Python 操作 MongoDB 讲解详细
2021-11-28 10:00:46

Python3正则匹配re.split,re.finditer及re.findall函数用法详解
2023-06-27 10:13:48
Oracle 存储过程加密方法
2009-10-23 18:02:00
Python爬虫爬取属于自己的地铁线路图
2021-09-10 11:46:23

nodeJS express路由学习req.body与req.query方法实例详解
2024-06-05 09:52:34

Python Pandas知识点之缺失值处理详解
2023-09-29 20:23:16

如何解决mysql重装失败方法介绍
2024-01-19 10:52:05
Python通过Manager方式实现多个无关联进程共享数据的实现
2021-12-27 04:03:17
详解Vue2的diff算法
2024-04-28 09:30:48

关于微信小程序获取小程序码并接受buffer流保存为图片的方法
2023-07-20 09:54:01
解决jupyter notebook import error但是命令提示符import正常的问题
2022-08-19 22:10:30
C#连接SQL数据库和查询数据功能的操作技巧
2024-01-19 03:31:03

python encode和decode的妙用
2021-01-08 01:34:20