访问未知路径时不显示自定义 500/404 错误页面
- 2025-02-17 09:25:00
- admin 原创
- 54
问题描述:
按照此处的教程,我无法创建自定义 500 或 404 错误页面。如果我输入了错误的 URL,页面会显示默认错误页面。我应该检查哪些内容才能阻止自定义页面显示?
文件目录:
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
我已经mysite/settings.py
启用了这些:
DEBUG = False
TEMPLATE_DEBUG = DEBUG
#....
TEMPLATE_DIRS = (
'C:/Users/Me/Django/mysite/templates',
)
之内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'),
)
我可以发布任何其他必要的代码,但如果我使用了错误的 URL,我应该进行哪些更改才能获得自定义 500 错误页面?
解决方案 1:
在您的主视图下添加您自己的以下两个视图的自定义实现,并使用您想要显示的内容views.py
设置模板404.html和500.html 。
使用此解决方案,无需添加自定义代码urls.py
代码如下:
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
更新
handler404
和handler500
是导出的 Django 字符串配置变量django/conf/urls/__init__.py
。这就是上述配置起作用的原因。
为了使上述配置起作用,您应该在urls.py
文件中定义以下变量,并将导出的 Django 变量指向定义这些 Django 功能视图的字符串 Python 路径,如下所示:
# project/urls.py
handler404 = '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_code = 404
return response
解决方案 2:
官方解答:
以下是有关如何设置自定义错误视图的官方文档链接:
https://docs.djangoproject.com/en/stable/topics/http/views/#customizing-error-views
它说在你的 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'
您还可以通过修改设置来自定义 CSRF 错误视图CSRF_FAILURE_VIEW
。
默认错误处理程序:
值得一读的是默认错误处理程序的文档page_not_found
,server_error
,permission_denied
和bad_request
。默认情况下,如果可以找到这些模板,它们会分别使用这些模板:404.html
,500.html
,403.html
和400.html
。
因此,如果您只想制作漂亮的错误页面,只需在目录中创建这些文件TEMPLATE_DIRS
,您根本不需要编辑 URLConf。阅读文档以查看哪些上下文变量可用。
在 Django 1.10 及更高版本中,默认的 CSRF 错误视图使用模板403_csrf.html
。
明白了:
不要忘记DEBUG
必须将其设置为 False 才能使它们起作用,否则将使用正常的调试处理程序。
解决方案 3:
在 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'
# ...
并在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
# ...
解决方案 4:
Django 3.0+ 4.0+
这是如何自定义错误视图的链接
这是如何呈现视图的链接
在urls.py
(主文件夹,在项目文件夹中)中输入:
handler404 = 'my_app_name.views.custom_page_not_found_view'
handler500 = 'my_app_name.views.custom_error_view'
handler403 = 'my_app_name.views.custom_permission_denied_view'
handler400 = 'my_app_name.views.custom_bad_request_view'
并在提到的应用程序(my_app_name
)中输入views.py
:
def custom_page_not_found_view(request, exception):
return render(request, "errors/404.html", {})
def custom_error_view(request, exception=None):
return render(request, "errors/500.html", {})
def custom_permission_denied_view(request, exception=None):
return render(request, "errors/403.html", {})
def custom_bad_request_view(request, exception=None):
return render(request, "errors/400.html", {})
注意: errors/404.html
如果您将文件放入项目(而不是应用程序)模板文件夹,则是路径templates/errors/404.html
,因此请将文件放在您想要的位置并写入正确的路径。
注 2:重新加载页面后,如果您仍然看到旧模板,请在 中更改settings.py
DEBUG=True
,保存,然后再次更改为False
并再次保存(这将重新启动服务器并收集新文件)。
解决方案 5:
从您引用的页面:
当您从视图中引发 Http404 时,Django 将加载一个专门用于处理 404 错误的特殊视图。它通过在您的根 URLconf 中查找变量 handler404 来找到它(并且仅在您的根 URLconf 中;在其他任何地方设置 handler404 都不会产生任何影响),这是一个采用 Python 点语法的字符串 - 与普通 URLconf 回调使用的格式相同。404 视图本身没有什么特别之处:它只是一个普通视图。
因此我相信您需要在 urls.py 中添加类似这样的内容:
handler404 = 'views.my_404_view'
和 handler500 类似。
解决方案 6:
在 Django 中3.x
,接受的答案将不起作用,因为render_to_response
已被完全删除,并且自接受的答案起作用的版本以来又做了一些更改。
还有其他一些答案,但我给出一个更清晰的答案:
在您的主urls.py
文件中:
handler404 = 'yourapp.views.handler404'
handler500 = 'yourapp.views.handler500'
在yourapp/views.py
文件中:
def handler404(request, exception):
context = {}
response = render(request, "pages/errors/404.html", context=context)
response.status_code = 404
return response
def handler500(request):
context = {}
response = render(request, "pages/errors/500.html", context=context)
response.status_code = 500
return response
确保您已导入render()
文件yourapp/views.py
:
from django.shortcuts import render
附注:render_to_response()
在 Django 中已被弃用2.x
,并在版本中被彻底删除3.x
。
解决方案 7:
如果您所需要的只是在出现 404 或 500 错误时显示包含一些奇特错误消息的自定义页面DEBUG = False
,则请在您的模板目录中添加两个名为 404.html 和 500.html 的模板,这样当出现 404 或 500 错误时它就会自动选择这些自定义页面。
解决方案 8:
不需要额外的视图。https ://docs.djangoproject.com/en/3.0/ref/views/
只需将错误文件放在模板目录的根目录中
404.html
400.html
403.html
500.html
当 debug 为 False 时,它应该使用你的错误页面
解决方案 9:
设置.py:
DEBUG = False
TEMPLATE_DEBUG = DEBUG
ALLOWED_HOSTS = ['localhost'] #provide your host name
然后将您的404.html
和500.html
页面添加到模板文件夹中。从民意调查应用程序的模板中删除404.html
和。500.html
解决方案 10:
在Django 2.*中,你可以在views.py中使用此构造
def handler404(request, exception):
return render(request, 'errors/404.html', locals())
在settings.py中
DEBUG = False
if DEBUG is False:
ALLOWED_HOSTS = [
'127.0.0.1:8000',
'*',
]
if DEBUG is True:
ALLOWED_HOSTS = []
在urls.py中
# https://docs.djangoproject.com/en/2.0/topics/http/views/#customizing-error-views
handler404 = 'YOUR_APP_NAME.views.handler404'
通常我会创建default_app并处理站点范围的错误和其中的上下文处理器。
解决方案 11:
出错时,在错误页面上找出 django 从哪里加载模板。我指的是路径堆栈。在基础中template_dir
添加这些 html 页面500.html
。404.html
当发生这些错误时,相应的模板文件将自动加载。
您还可以添加其他错误代码的页面,例如400和403。
解决方案 12:
作为一行(针对 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)
解决方案 13:
# views.py
def handler404(request, exception):
context = RequestContext(request)
err_code = 404
response = render_to_response('404.html', {"code":err_code}, context)
response.status_code = 404
return response
# <project_folder>.urls.py
handler404 = 'todo.views.handler404'
这适用于 django 2.0
请确保将您的自定义内容包含404.html
在应用程序模板文件夹内。
解决方案 14:
尝试将您的错误模板移至.../Django/mysite/templates/
。
我不太确定这一点,但我认为这些对于网站来说需要是“全局的”。
解决方案 15:
在 Django 根 urls.py 文件中,添加以下行
from django.conf.urls import (handler400, handler403, handler404, handler500)
handler400 = 'app.views.bad_request'
handler403 = 'app.views.permission_denied'
handler404 = 'app.views.page_not_found'
handler500 = 'app.views.server_error'
在应用程序的 views.py 文件中,创建相应的函数。
def server_error(request, exception=None):
# return render(request, '500.html')
return redirect('/')
最后,在 settings.py 文件中,设置DEBUG = False
解决方案 16:
您不需要做任何花哨的事情,只需404.html
在模板中创建一个文件即可。转到settings.py
并设置:
DEBUG = False
ALLOWED_HOSTS = ["*"]
它会自动覆盖默认值。
解决方案 17:
我还有
TEMPLATE_DIRS
在我内心深处settings.py
,这就是问题所在。
该答案是作为对问题Django 的编辑发布的,由 OP reZach在 CC BY-SA 3.0 下创建自定义 500/404 错误页面。
解决方案 18:
Django > 2.2
from django.shortcuts import render_to_response, render
from django.template import RequestContext
def handler500(request, *args, **argv):
context = {}
print(request.body, '==========')
response = render(request, '500.jinja', context=context)
response.status_code = 500
return response
在 urls.py 中
handler500 = 'apps.core.views.handler500'
解决方案 19:
简单方法:
要快速为错误创建自定义错误页面404
,请将名为的文件放在404.html
根模板目录中。对于其他错误(如400
、500
和403
),请遵循相同的模式,分别在同一根模板目录中创建400.html
、500.html
和403.html
来源:Django 关于提供静态文件的文档
方法 2:
要在 Django 中自定义错误页面,请按照以下步骤操作:
打开你的 Django 根
urls.py
文件。添加以下行以将特定视图与不同的错误代码关联:
from django.conf.urls import (handler400, handler403, handler404, handler500)
handler400 = 'app.views.bad_request'
handler403 = 'app.views.permission_denied'
handler404 = 'app.views.page_not_found'
handler500 = 'app.views.server_error'
将'app.views.bad_request'
、'app.views.permission_denied'
、'app.views.page_not_found'
和替换'app.views.server_error'
为处理每个错误的自定义视图函数的实际路径。
来源:Django 自定义错误视图文档
请记住,如果
DEBUG
您的配置中的设置被设置为True
,则404
您创建的自定义页面可能不会显示。相反,Django 将显示 URL 配置以及调试信息。
解决方案 20:
在 中urls.py
输入此代码:
from django.conf.urls import (handler400, handler403, handler404, handler500)
handler404 = 'my_app.views.page_not_found_view'
然后在你的views.py中添加此代码
from django.shortcuts import render,get_object_or_404
def page_not_found_view(request, exception):
return render(request, '404.html', status=404)
在笔记本电脑上测试时,不要忘记设置DEBUG = False
和设置。ALLOWED_HOSTS = [127.0.0.1]
扫码咨询,免费领取项目管理大礼包!