栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Django,创建自定义500/404错误页面

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Django,创建自定义500/404错误页面

在你的主要内容下,

views.py
添加你自己的以下两个视图的自定义实现,然后只需设置要显示的模板404.html和
500.html

使用此解决方案,无需将自定义代码添加到

urls.py

这是代码:

from django.shortcuts import render_to_responsefrom django.template import RequestContextdef handler404(request, *args, **argv):    response = render_to_response('404.html', {}, context_instance=RequestContext(request))    response.status_pre = 404    return responsedef handler500(request, *args, **argv):    response = render_to_response('500.html', {}, context_instance=RequestContext(request))    response.status_pre = 500    return response

更新资料

handler404
handler500
导出的Django字符串配置变量
django/conf/urls/__init__.py
。这就是为什么上面的配置起作用的原因。

为了使上述配置生效,你应该在

urls.py
文件中定义以下变量,并将导出的Django变量指向定义这些Django功能视图的字符串Python路径,如下所示:

# project/urls.pyhandler404 = 'my_app.views.handler404'handler500 = 'my_app.views.handler500'

Django 2.0更新

处理程序视图的签名在Django 2.0中已更改:https : //docs.djangoproject.com/en/2.0/ref/views/#error-views

如果你使用上述视图,则handler404将失败并显示以下消息:

“ handler404()获得了意外的关键字参数’exception’”

在这种情况下,请修改你的视图,如下所示:

def handler404(request, exception, template_name="404.html"):    response = render_to_response(template_name)    response.status_pre = 404    return response


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/390546.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号