Django创建一个自定义的500/404错误页面

时间:2022-10-09 21:03:13

Following the tutorial found here exactly, 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 /设置。py我已经启用了:

DEBUG = False
TEMPLATE_DEBUG = DEBUG

#....

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

within mysite/polls/urls.py:

在mysite /调查/ 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

在我的设置。这就是问题所在

11 个解决方案

#1


71  

Under your main views.py add your own custom implementation of the following two views, and just set up the templates 404.html and 500.html with what you want to display.

在你的主要观点。py为以下两个视图添加了您自己的自定义实现,并只设置了templates 404。html和500。html与您想要显示的内容。

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

使用这个解决方案,无需向url .py添加自定义代码

Here's the code:

这是代码:

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


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


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

Update

更新

handler404 and handler500 are exported Django string configuration variables found in django/conf/urls/__init__.py. That is why the above config works.

handler404和handler500是在Django /conf/url /__init__.py中找到的Django字符串配置变量。这就是为什么上面的配置是有效的。

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

要使上述配置生效,您应该在url中定义这些变量。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()得到一个意外的关键字参数‘exception’”

In such case modify your views like this:

在这种情况下,修改你的观点如下:

def handler404(request, exception, template_name='404.html'):
    ... 

#2


38  

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_FAILURE_VIEW来定制CSRF错误视图。

Default error handlers:

It's worth reading the documentation of the default error handlers, page_not_found, server_error, permission_denied and 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_found、server_error、permission_denied和bad_request的文档是值得的。默认情况下,如果可以找到这些模板,它们将使用这些模板,分别是:404。html,500。html,403。html 400.和html。

So if all you want to do is make pretty error pages, just create those files in a TEMPLATE_DIRS directory, 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 DEBUG must be set to False for these to work, otherwise, the normal debug handlers will be used.

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

#3


28  

Add these lines in urls.py

在urls.py中添加这些行

urls.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

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

# ...

#4


19  

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:

所以我认为你需要在你的瓶子里加上这样的东西。

handler404 = 'views.my_404_view'

and similar for handler500.

并为handler500相似。

#5


15  

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时,它将自动选择这个自定义页面。

#6


7  

settings.py::::

settings.py::::

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

and just add your 404.html and 500.html pages in templates folder. remove 404.html and 500.html from templates in polls app.

再加上404。html和500。在模板文件夹中的html页面。删除404。html和500。从民意调查应用的模板html。

#7


6  

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

犯一个错误,在错误页面上找到django正在加载模板的位置。我是说路径堆栈。在基本的template_dir中添加这些html页面500。html 404. html。当这些错误发生时,相应的模板文件将被自动加载。

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

您还可以为其他错误代码添加页面,比如400和403。

Hope this help !!!

希望这帮助! ! !

#8


5  

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)

#9


5  

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_app and handle site-wide errors, context processors in it.

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

#10


3  

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

尝试将错误模板移动到……/ Django / mysite /模板/ ?

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

我确信这一点,但我认为这些需要“全球化”的网站。

#11


0  

For django 2 follow this teps:

对于django 2,请遵循以下tep:

edit your project/settings.py file to show this error

编辑您的项目/设置。py文件显示此错误

DEBUG = False
ALLOWED_HOSTS = ['127.0.0.1','localhost']

Add this to views.py:

添加这个views.py:

def error_404_view(request, exception):
    return render(request,'myapp/404.html')

Create a custom 404.html file.

创建一个自定义404。html文件。

Now go to urls.py file of your project and add this line after url patterns:

现在去的url。项目的py文件,在url模式之后添加这一行:

handler404 = 'myapp.views.error_404_view'

Now if you go to your browser and open any non-existent URL, you will be shown custom 404 error page.

现在,如果您打开浏览器并打开任何不存在的URL,您将看到自定义404错误页面。

#1


71  

Under your main views.py add your own custom implementation of the following two views, and just set up the templates 404.html and 500.html with what you want to display.

在你的主要观点。py为以下两个视图添加了您自己的自定义实现,并只设置了templates 404。html和500。html与您想要显示的内容。

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

使用这个解决方案,无需向url .py添加自定义代码

Here's the code:

这是代码:

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


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


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

Update

更新

handler404 and handler500 are exported Django string configuration variables found in django/conf/urls/__init__.py. That is why the above config works.

handler404和handler500是在Django /conf/url /__init__.py中找到的Django字符串配置变量。这就是为什么上面的配置是有效的。

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

要使上述配置生效,您应该在url中定义这些变量。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()得到一个意外的关键字参数‘exception’”

In such case modify your views like this:

在这种情况下,修改你的观点如下:

def handler404(request, exception, template_name='404.html'):
    ... 

#2


38  

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_FAILURE_VIEW来定制CSRF错误视图。

Default error handlers:

It's worth reading the documentation of the default error handlers, page_not_found, server_error, permission_denied and 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_found、server_error、permission_denied和bad_request的文档是值得的。默认情况下,如果可以找到这些模板,它们将使用这些模板,分别是:404。html,500。html,403。html 400.和html。

So if all you want to do is make pretty error pages, just create those files in a TEMPLATE_DIRS directory, 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 DEBUG must be set to False for these to work, otherwise, the normal debug handlers will be used.

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

#3


28  

Add these lines in urls.py

在urls.py中添加这些行

urls.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

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

# ...

#4


19  

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:

所以我认为你需要在你的瓶子里加上这样的东西。

handler404 = 'views.my_404_view'

and similar for handler500.

并为handler500相似。

#5


15  

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时,它将自动选择这个自定义页面。

#6


7  

settings.py::::

settings.py::::

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

and just add your 404.html and 500.html pages in templates folder. remove 404.html and 500.html from templates in polls app.

再加上404。html和500。在模板文件夹中的html页面。删除404。html和500。从民意调查应用的模板html。

#7


6  

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

犯一个错误,在错误页面上找到django正在加载模板的位置。我是说路径堆栈。在基本的template_dir中添加这些html页面500。html 404. html。当这些错误发生时,相应的模板文件将被自动加载。

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

您还可以为其他错误代码添加页面,比如400和403。

Hope this help !!!

希望这帮助! ! !

#8


5  

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)

#9


5  

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_app and handle site-wide errors, context processors in it.

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

#10


3  

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

尝试将错误模板移动到……/ Django / mysite /模板/ ?

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

我确信这一点,但我认为这些需要“全球化”的网站。

#11


0  

For django 2 follow this teps:

对于django 2,请遵循以下tep:

edit your project/settings.py file to show this error

编辑您的项目/设置。py文件显示此错误

DEBUG = False
ALLOWED_HOSTS = ['127.0.0.1','localhost']

Add this to views.py:

添加这个views.py:

def error_404_view(request, exception):
    return render(request,'myapp/404.html')

Create a custom 404.html file.

创建一个自定义404。html文件。

Now go to urls.py file of your project and add this line after url patterns:

现在去的url。项目的py文件,在url模式之后添加这一行:

handler404 = 'myapp.views.error_404_view'

Now if you go to your browser and open any non-existent URL, you will be shown custom 404 error page.

现在,如果您打开浏览器并打开任何不存在的URL,您将看到自定义404错误页面。