Django,自定义错误页面重定向到500,而不是404 [英] Django, custom error pages redirects to 500 instead of 404

查看:71
本文介绍了Django,自定义错误页面重定向到500,而不是404的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的生产服务器具有以下设置:

I have production server which has these settings:

DEBUG = False
ALLOWED_HOSTS = ['localhost', '127.0.0.1', 'my.ip.address', 'example.com']

然后在我的主要 urls.py 文件中,添加了以下内容:

Then in my main urls.py file I have added this:

from django.conf.urls import url, include, handler404, handler500

handler500 = 'main.views.error_500'
handler404 = 'main.views.error_404'

我的 main.views 有以下内容:

def error_404(request):
    return render(request, 'main/errors/404.html', status=404)


def error_500(request):
    return render(request, 'main/errors/500.html', status=500)

当我部署生产服务器并尝试打开不存在的页面时,它应该重定向到我的 error_404 视图。但是,它重定向到我的 error_500 视图。为什么会这样?

When I deploy my production server and try to open page that does not exists, it should redirect to my error_404 view. However, it redirects to my error_500 view. Why this is happening?

推荐答案

这个问题已经三个月了,但是对于社区来说,这就是我如何解决这个问题:

This question is three months old but for the community this is how I solved this:

无法找到404页的视图需要一个 exception参数:

The 404-page-not-found-view needs an "exception" argument:

def error_404(request, exception):
    return render(request,'myapp/404.html', status = 404)




默认的404视图会将两个变量传递给模板:
request_path(导致错误的URL)和
异常,它是
触发视图的异常的有用表示(例如,包含传递给特定
Http404实例的任何消息)。

The default 404 view will pass two variables to the template: request_path, which is the URL that resulted in the error, and exception, which is a useful representation of the exception that triggered the view (e.g. containing any message passed to a specific Http404 instance).

来源: https://docs.djangoproject.com/zh-CN/2.1/ref/views/#the-404-page-not-found-view

我是Django-noob,但我假设没有此参数,则404会触发500。

I'm Django-noob but I suppose that without this argument the 404 trigger a 500.

另一件事:它对我有用,无需导入: from django.conf.urls import handler404,handler500

One more thing: It works for me without the import : "from django.conf.urls import handler404, handler500"

这篇关于Django,自定义错误页面重定向到500,而不是404的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆