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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17662928/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:50:06  来源:igfitidea点击:

Django, creating a custom 500/404 error page

pythondjangodjango-templateshttp-status-code-404

提问by Zac

Following the tutorial found hereexactly, I cannot create a custom 500 or 404 error page. If I do type in a bad url, the page gives me the default error page. Is there anything I should be checking for that would prevent a custom page from showing up?

完全按照此处找到的教程,我无法创建自定义 500 或 404 错误页面。如果我输入了错误的 url,该页面会为我提供默认的错误页面。有什么我应该检查的东西会阻止自定义页面显示吗?

File directories:

文件目录:

mysite/
    mysite/
        __init__.py
        __init__.pyc
        settings.py
        settings.pyc
        urls.py
        urls.pyc
        wsgi.py
        wsgi.pyc
    polls/
        templates/
            admin/
                base_site.html
            404.html
            500.html
            polls/
                detail.html
                index.html
        __init__.py
        __init__.pyc
        admin.py
        admin.pyc
        models.py
        models.pyc
        tests.py
        urls.py
        urls.pyc
        view.py
        views.pyc
    templates/
    manage.py

within mysite/settings.py I have these enabled:

在 mysite/settings.py 中,我启用了这些:

DEBUG = False
TEMPLATE_DEBUG = DEBUG

#....

TEMPLATE_DIRS = (
    'C:/Users/Me/Django/mysite/templates', 
)

within mysite/polls/urls.py:

在 mysite/polls/urls.py 中:

from django.conf.urls import patterns, url

from polls import views

urlpatterns = patterns('',
    url(r'^$', views.index, name='index'),
    url(r'^(?P<poll_id>\d+)/$', views.detail, name='detail'),
    url(r'^(?P<poll_id>\d+)/results/$', views.results, name='results'),
    url(r'^(?P<poll_id>\d+)/vote/$', views.vote, name='vote'),
)

I can post any other code necessary, but what should I be changing to get a custom 500 error page if I use a bad url?

我可以发布任何其他必要的代码,但是如果我使用错误的 url,我应该更改什么以获得自定义 500 错误页面?

Edit

编辑

SOLUTION:I had an additional

解决方案:我有一个额外的

TEMPLATE_DIRS

within my settings.py and that was causing the problem

在我的 settings.py 中,这导致了问题

回答by Mike Pelley

From the page you referenced:

从您引用的页面:

When you raise Http404 from within a view, Django will load a special view devoted to handling 404 errors. It finds it by looking for the variable handler404 in your root URLconf (and only in your root URLconf; setting handler404 anywhere else will have no effect), which is a string in Python dotted syntax – the same format the normal URLconf callbacks use. A 404 view itself has nothing special: It's just a normal view.

当您从视图中引发 Http404 时,Django 将加载一个专门用于处理 404 错误的特殊视图。它通过在您的根 URLconf 中查找变量 handler404 来找到它(并且仅在您的根 URLconf 中;在其他任何地方设置 handler404 都没有效果),这是 Python 点分语法中的字符串——与普通 URLconf 回调使用的格式相同。404 视图本身没有什么特别之处:它只是一个普通视图。

So I believe you need to add something like this to your urls.py:

所以我相信你需要在你的 urls.py 中添加这样的东西:

handler404 = 'views.my_404_view'

and similar for handler500.

和 handler500 类似。

回答by astrognocci

Try moving your error templates to .../Django/mysite/templates/?

尝试将您的错误模板移至.../Django/mysite/templates/?

I'm note sure about this one, but i think these need to be "global" to the website.

我很确定这个,但我认为这些需要是“全球”的网站。

回答by Aaron Lelevier

Under your main views.pyadd your own custom implementation of the following two views, and just set up the templates 404.htmland 500.htmlwith what you want to display.

在您的 main 下views.py添加您自己的以下两个视图的自定义实现,只需设置模板404.html500.html即可显示您想要显示的内容。

With this solution, no custom code needs to be added to urls.py

使用此解决方案,无需添加自定义代码 urls.py

Here's the code:

这是代码:

from django.shortcuts import render_to_response
from django.template import RequestContext


def handler404(request, *args, **argv):
    response = render_to_response('404.html', {},
                                  context_instance=RequestContext(request))
    response.status_code = 404
    return response


def handler500(request, *args, **argv):
    response = render_to_response('500.html', {},
                                  context_instance=RequestContext(request))
    response.status_code = 500
    return response

Update

更新

handler404and handler500are exported Django string configuration variables found in django/conf/urls/__init__.py. That is why the above config works.

handler404handler500导出在django/conf/urls/__init__.py. 这就是上述配置有效的原因。

To get the above config to work, you should define the following variables in your urls.pyfile and point the exported Django variables to the string Python path of where these Django functional views are defined, like so:

要使上述配置起作用,您应该在urls.py文件中定义以下变量,并将导出的 Django 变量指向定义这些 Django 功能视图的字符串 Python 路径,如下所示:

# project/urls.py

handler404 = 'my_app.views.handler404'
handler500 = 'my_app.views.handler500'

Update for Django 2.0

更新 Django 2.0

Signatures for handler views were changed in Django 2.0: https://docs.djangoproject.com/en/2.0/ref/views/#error-views

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

If you use views as above, handler404 will fail with message:

如果您使用上述视图,handler404 将失败并显示消息:

"handler404() got an unexpected keyword argument 'exception'"

“handler404() 得到了一个意外的关键字参数‘异常’”

In such case modify your views like this:

在这种情况下,像这样修改您的视图:

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

回答by FireZenk

As one single line (for 404 generic page):

作为一行(用于 404 通用页面):

from django.shortcuts import render_to_response
from django.template import RequestContext

return render_to_response('error/404.html', {'exception': ex},
                                      context_instance=RequestContext(request), status=404)

回答by Armance

Add these lines in urls.py

在 urls.py 中添加这些行

urls.py

网址.py

from django.conf.urls import (
handler400, handler403, handler404, handler500
)

handler400 = 'my_app.views.bad_request'
handler403 = 'my_app.views.permission_denied'
handler404 = 'my_app.views.page_not_found'
handler500 = 'my_app.views.server_error'

# ...

and implement our custom views in views.py.

并在 views.py 中实现我们的自定义视图。

views.py

视图.py

from django.shortcuts import (
render_to_response
)
from django.template import RequestContext

# HTTP Error 400
def bad_request(request):
    response = render_to_response(
        '400.html',
        context_instance=RequestContext(request)
        )

        response.status_code = 400

        return response

# ...

回答by Rakesh babu

settings.py:

设置.py:

DEBUG = False
TEMPLATE_DEBUG = DEBUG
ALLOWED_HOSTS = ['localhost']  #provide your host name

and just add your 404.htmland 500.htmlpages in templates folder. remove 404.htmland 500.htmlfrom templates in polls app.

只需在模板文件夹中添加您的404.html500.html页面。从投票应用程序中的模板中删除404.html和删除500.html

回答by Flimm

Official answer:

官方回复:

Here is the link to the official documentation on how to set up custom error views:

这是有关如何设置自定义错误视图的官方文档的链接:

https://docs.djangoproject.com/en/stable/topics/http/views/#customizing-error-views

https://docs.djangoproject.com/en/stable/topics/http/views/#customizing-error-views

It says to add lines like these in your URLconf (setting them anywhere else will have no effect):

它说在你的 URLconf 中添加这样的行(将它们设置在其他任何地方都没有效果):

handler404 = 'mysite.views.my_custom_page_not_found_view'
handler500 = 'mysite.views.my_custom_error_view'
handler403 = 'mysite.views.my_custom_permission_denied_view'
handler400 = 'mysite.views.my_custom_bad_request_view'

You can also customise the CSRF error view by modifying the setting CSRF_FAILURE_VIEW.

您还可以通过修改设置来自定义 CSRF 错误视图CSRF_FAILURE_VIEW

Default error handlers:

默认错误处理程序:

It's worth reading the documentation of the default error handlers, page_not_found, server_error, permission_deniedand bad_request. By default, they use these templates if they can find them, respectively: 404.html, 500.html, 403.html, and 400.html.

值得阅读默认错误处理程序page_not_foundserver_errorpermission_denied和的文档bad_request。默认情况下,他们使用这些模板,如果他们可以分别找到他们,: ,404.html500.html403.html400.html

So if all you want to do is make pretty error pages, just create those files in a TEMPLATE_DIRSdirectory, you don't need to edit URLConf at all. Read the documentation to see which context variables are available.

因此,如果您只想制作漂亮的错误页面,只需在TEMPLATE_DIRS目录中创建这些文件,您根本不需要编辑 URLConf。阅读文档以查看哪些上下文变量可用。

In Django 1.10 and later, the default CSRF error view uses the template 403_csrf.html.

在 Django 1.10 及更高版本中,默认的 CSRF 错误视图使用模板403_csrf.html

Gotcha:

陷阱:

Don't forget that DEBUGmust be set to False for these to work, otherwise, the normal debug handlers will be used.

不要忘记DEBUG必须将它们设置为 False 才能使它们工作,否则将使用正常的调试处理程序。

回答by allsyed

Make an error, On the error page find out from where django is loading templates.I mean the path stack.In base template_diradd these html pages 500.html, 404.html. When these errors occur the respective template files will be automatically loaded.

犯一个错误,在错误页面上找出 django 从哪里加载模板。我的意思是路径堆栈。在基础template_dir 中添加这些 html 页面500.html404.html。发生这些错误时,将自动加载相应的模板文件。

You can add pages for other error codes too, like 400and 403.

您也可以为其他错误代码添加页面,例如400403

Hope this help !!!

希望这有帮助!!!

回答by Krishna G Nair

If all you need is to show custom pages which have some fancy error messages for your site when DEBUG = False, then add two templates named 404.html and 500.html in your templates directory and it will automatically pick up this custom pages when a 404 or 500 is raised.

如果您需要的只是显示带有一些奇特错误消息的自定义页面DEBUG = False,则在模板目录中添加两个名为 404.html 和 500.html 的模板,当出现 404 或 500被提出。

回答by DeN

In Django 2.*you can use this construction in views.py

Django 2.* 中,你可以在views.py 中使用这个结构

def handler404(request, exception):
    return render(request, 'errors/404.html', locals())

In settings.py

settings.py中

DEBUG = False

if DEBUG is False:
    ALLOWED_HOSTS = [
        '127.0.0.1:8000',
        '*',
    ]

if DEBUG is True:
    ALLOWED_HOSTS = []

In urls.py

urls.py 中

# https://docs.djangoproject.com/en/2.0/topics/http/views/#customizing-error-views
handler404 = 'YOUR_APP_NAME.views.handler404'

Usually i creating default_appand handle site-wide errors, context processors in it.

通常我创建default_app并处理站点范围的错误,其中的上下文处理器。