具有多个应用程序的我的 Django 项目的通用 404 和 500 页面
Common 404 & 500 Page for My Django Project having multiple application
我正在开发一个包含多个应用程序的 Django 项目。我想要所有应用程序的通用 404 和 500 错误页面。我应该怎么做?
我已经为每个应用实现了单独的错误页面,并且运行良好。但是我想要一个公共页面,它应该放在我的主项目文件夹中。
在您的模板目录中创建模板 custom404.html
和 custom500.html
如果特定于应用程序,则将其添加到您的 urls.py
底部,或者在 urls.py
中将 url 添加到其他应用程序
handler404 = 'custom_views.handler404'
handler500 = 'custom_views.handler500'
并在 custom_views
根文件中定义一次这样的视图
from django.shortcuts import render_to_response
def handler404(request, *args, **kwargs):
response = render_to_response('custom404.html', context = {})
response.status_code = 404
return response
def handler500(request, *args, **kwargs):
response = render_to_response('custom500.html', context={})
response.status_code = 500
return response
这会将您的 404,500 url 路由到您正在构建模板并呈现它的模板视图
最简单的方法是在 BASE_DIR
中创建一个 templates
目录,即包含 manage.py
的目录
在您的设置中添加该目录的路径
TEMPLATES = [
{
...
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
...
]
然后只需在 templates
目录中创建错误页面即可。
示例:如果要为错误 404 创建一个页面,则在 templates
目录中创建一个名为 404.html 的文件。
我正在开发一个包含多个应用程序的 Django 项目。我想要所有应用程序的通用 404 和 500 错误页面。我应该怎么做?
我已经为每个应用实现了单独的错误页面,并且运行良好。但是我想要一个公共页面,它应该放在我的主项目文件夹中。
在您的模板目录中创建模板 custom404.html
和 custom500.html
如果特定于应用程序,则将其添加到您的 urls.py
底部,或者在 urls.py
中将 url 添加到其他应用程序
handler404 = 'custom_views.handler404'
handler500 = 'custom_views.handler500'
并在 custom_views
根文件中定义一次这样的视图
from django.shortcuts import render_to_response
def handler404(request, *args, **kwargs):
response = render_to_response('custom404.html', context = {})
response.status_code = 404
return response
def handler500(request, *args, **kwargs):
response = render_to_response('custom500.html', context={})
response.status_code = 500
return response
这会将您的 404,500 url 路由到您正在构建模板并呈现它的模板视图
最简单的方法是在 BASE_DIR
中创建一个 templates
目录,即包含 manage.py
的目录
在您的设置中添加该目录的路径
TEMPLATES = [
{
...
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
...
]
然后只需在 templates
目录中创建错误页面即可。
示例:如果要为错误 404 创建一个页面,则在 templates
目录中创建一个名为 404.html 的文件。